Transferred from: http://blog.csdn.net/violet_day/article/details/17403207
$http
The $http service is based on the $Q service and provides a promise package that accepts a configuration object parameter and returns a Promise object. It also provides 2 methods for defining promise Callbacks: Success and error.
[JavaScript]View Plaincopy
- $http ({method: "GET", url:"/someurl"}).
- Success (function (data, status, headers, config) {
- triggered when an asynchronous request returns a response successfully
- }). Error (function (data, status, headers, config) {
- //Triggers when an exception occurs
- });
Because of the number of common HTTP requests, $http service implements a convenient way to do so, for example:
$http. Get
$http. Post
$http. Put
$http. Delete
$http. Head
$http. Jsonp
The $http automatically adds an HTTP header for each request, and can be configured with $httpprovider.defaults.headers.
$httpProvider. Defaults.headers.common sets the header information that all requests will contain:
Accept:application/json, Text/plain, */*
X-requested-with:xmlhttprequest
$httpProvider. Defaults.headers.post set the default request header for the POST request:
Content-type:application/json
$httpProvider. Defaults.headers.put sets the default request header for put requests:
Content-type:application/json
In addition, for the cache feature of $http, it is recommended to take a look at this article.
So $http the relevant content, first of all.
Now, let's take a look at $resource and note that the service requires us to manually load the Angular-resource.js file ~
The core value of $resource service is that it provides a better user experience for developers to interact with restful style webservices, which encapsulates lower-level $http so that the front-end developers are not required to write large amounts of asynchronous request code.
How to configure $resource service:
[JavaScript]View Plaincopy
- $resource (url[, paramdefaults][, Actions]);
wr.
String type, where placeholders can appear, placeholders are prefixed with ":", and if the system's domain name has a port number, it needs to be escaped manually:
Http://www.codingcool.com:8080/api should be so incoming:
[JavaScript]View Plaincopy
- $resource ("Http://www.codingcool.com\\:8080/api");
This situation in the 1.2.0RC1 version of NG does not exist, the port number will be recognized without the need to manually escape ~ ~
Paramdefaults (optional)
Object type, which sets the default value of the parameter, which can be overridden by the actions (the third parameter). If the parameter value you set is a function, the function will be executed each time it gets its value (with a bit of nonsense).
Parameters that are set that do not appear in the URL template (the first parameter) are added as search query, for example:
If the URL template is/codingcool/:author,paramdefaults {author: "Kazaff", Profession: "Geek"}, then the final request URL becomes:
/codingcool/kazaff?profession=geek
If the parameter value starts with "@", its true value will be extracted from the data object, followed by an example.
Actions (optional)
An object type that defines the available methods that the $resource provides, as well as the declaration details and $http.
Here's another look at the return value of $resource:
The type of the return value is an object that contains all the methods that interact with the specified service API (that is, the URL), which by default contains the following default method:
[JavaScript]View Plaincopy
- { ' get ': {method:' get '},
- ' Save ': {method:' POST '},
- ' query ': {method:' GET ', IsArray:true},
- ' Remove ': {method:' DELETE '},
- ' Delete ': {method:' delete '}
- };
These methods call the built-in $http service ~
When the asynchronous request succeeds, the data is retrieved from the server side and encapsulated in an object instance of the $resource service, which can be manipulated directly by the Save,remove,delete method, which encapsulates and provides a simple crud operation, So that developers can feel respected Ah! hehe ~
[JavaScript]View Plaincopy
- var User = $resource ('/user/:userid ', {userId:' @id '});
- var user = User.get ({userid:123}, function () {
- USER.ABC = true;
- User. $save ();
- });
Notice "@id" and "$save ()" In the code above, and when you execute $save, User.ID will be sent the request as the value of the UserID when the @ is used.
Encapsulating Ajax in this way not only makes the code more elegant, but also works with Ng's view rendering: The template engine does not render when the data is not returned, and once the asynchronous data acquisition is complete, the template engine's rendering mechanism is automatically triggered to render the data into the view.
Finally, look at a simple example:
Angularjs's $resource
[HTML]View Plaincopy
- <! DOCTYPE HTML>
- <HTML ng-app="Demo">
- <head>
- <Meta charset=utf-8 />
- <title>ngresource DEMO</title>
- </head>
- <body>
- <div ng-controller="Geeklistctrl">
- <ul>
- <li ng-repeat="geek in Geeks">
- <a href="#" ng-click="show ({{geek.id}})">{{geek.name}}</a>
- </li>
- </ul>
- <div ng-show="user">
- {{user.msg}}
- </div>
- </div>
- <script src="./src/angular.js"></script>
- <script src="./src/angular-resource.js"></script>
- <script type="Text/javascript">
- var demo = angular.module (' demo ', ["Ngresource"])
- . Factory (' Geek ', function ($resource) {
- Return $resource ("Geek/:geekid.json", {}, {
- Query: {
- Method: "GET",
- Params: {geekid: "List"},
- Isarray:true
- }
- });
- });
- function Geeklistctrl ($scope, Geek) {
- $Scope.geeks = geek.query ();
- $scope.show = function (ID) {
- $Scope.user = geek.get ({geekid:id});
- };
- }
- function Geekdetailctrl ($scope, $routeParams, Geek) {
- $Scope.geek = geek.get ({geekid: $routeParams. Geekid}, function (geek) {
- Console.dir (geek);
- });
- }
- </Script>
- </body>
- </html>
Turn from:
[Turn]angularjs's $resource