Angular learning notes (-appendix 1)-$ Resource Method

Source: Internet
Author: User

Resources obtained through $ resource or resources instantiated through $ resource have some methods, such as $ save, which can be called directly to save the resource:

For example, there is a service created by $ Resource:

var service = angular.module(‘myRecipe.service‘,[‘ngResource‘]);service.factory(‘Recipe‘,[‘$resource‘,function($resource){    return $resource(‘/recipe/:id‘,{id:‘@id‘});}]);service.factory(‘loadRecipes‘,[‘Recipe‘,‘$q‘,function(Recipe,$q){    return function(){        var defer = $q.defer();        Recipe.query(function(recipes){            defer.resolve(recipes)        },function(err){            defer.reject(err)        });        return defer.promise    }}]);service.factory(‘loadRecipe‘,[‘Recipe‘,‘$q‘,‘$route‘,‘$routeParams‘,function(Recipe,$q,$route,$routeParams){    return function(){        var defer = $q.defer();        Recipe.get({id:$route.current.params.recipeId},function(recipe){            defer.resolve(recipe)        },function(err){            defer.reject(err)        });        return defer.promise    }}]);

Then I obtained a recipe through the loadrecipe method. After modifying the recipe, I need to submit and save it. The following two methods are the same:

1. Use the Save method of $ resource (the first parameter is requested, and the second parameter is the callback after the request is completed)

        Recipe.save($scope.recipe,function(){            $location.path(‘/view/‘+$scope.recipe.id)        });

2. Because the recipe itself is the resource obtained through $ resource, it has the $ save method. The function in the $ save method is the callback after the SAVE is successful.

        $scope.recipe.$save(function(){            $location.path(‘/view/‘+$scope.recipe.id)        });

In addition to the resources obtained through loadrecipe, resources instantiated through $ resource also have the $ save method:

For example, the following recipe:

    $scope.recipe = new Recipe({        ingredients:[{}]    });    $scope.save = function(invalid){        if(invalid){            return false        }        Recipe.save($scope.recipe,function(recipe){            $location.path(‘/view/‘+recipe.id)        });    };

In $ resource (), the second parameter {ID: '@ id'} indicates that: ID in the URL will use the ID attribute value of the resource, that is, the ID attribute value of the recipe.

 

You can also use the third parameter $ resource () to customize the resource method:

return $resource(‘/card/user/:userID/:id‘,{userID:123,id:‘@id‘},{charge:{method:‘POST‘,params:{charge:true},isArray:false}})

To analyze the third parameter {charge: {method: 'post', Params: {charge: true}, isarray: false }}

1. charge is the name of a custom method. Resources can call this custom method through $ charge ().

2. The charge property value is a JSON object with three attributes:

Method: Request Method of this method: 'post', 'get', 'delete', 'put', etc...

Params: defines the parameter after the request URL. Here is {charge: true}, it will be directed to the URL? Charge = true send request

Isarray: defines whether the returned data format is an array.

Eg:

HttpREST.factory(‘cardResource‘,function($resource){    return $resource(‘/card/user/:userID/:id‘,{userID:123,id:‘@id‘},{charge:{method:‘POST‘,params:{charge:true},isArray:false}})});HttpREST.factory(‘httpCard‘,function($q,cardResource){    return {        getById:function(cardID){            var defer = $q.defer();            cardResource.get({id:cardID},function(data,headers){                defer.resolve(data);            },function(data,headers){                defer.reject(data);            });            return defer.promise        }    }});$scope.addCharge = function(){    $scope.card_1.then(function(card){         card.$charge({amount:100});    })}

Note: card_1 obtains the promise object instead of the resource itself. To obtain the actual resource, you need to obtain it through the function parameters in its then method. For details about this problem, refer:

Http://www.cnblogs.com/liulangmao/p/3907307.html

$ The parameters in charge indicate the parameters following the URL, that is:

Card. $ charge ({amount: 100}) to/card/user/123/1? Charge = turn & amount = 100 sent the POST request, and the request body is card

1 In the request URL is the ID of the card because {ID: @ ID} is configured in the second parameter of $ resource,

The request parameter is charge = true because {charge: {Params: {charge: true} is configured in the third parameter $ resource }}
The request method is post because {charge: {method: 'post', Params: {charge: true} is configured in the third parameter of $ resource }}}

The request parameter is amount = 100 because the parameter {amount: 100} is passed in when card. $ charge () is called}
 

The method of a resource has another feature: after the request is complete, the resource that calls the method is automatically filled with the return value, and the view is updated. Manual processing is not required in the callback:

Eg:

HTML:

<Button ng-click = "addcharge () "> recharge the China Construction Bank Card for 100 RMB </button> <br/> <span >{{ card_1 ['name'] }</span> <span >{{ card_1 ['amount '] }}</span> <br/>

JS:

    $scope.addCharge = function(){        $scope.card_1.then(function(card){            card.$charge({amount:100});        })    }

Node:

app.post(‘/card/user/123/:id‘,function(req,res){    var index = req.params.id ? req.params.id-1 : cards.length;    var query = url.parse(req.url,true)[‘query‘];    if (query.charge){        cards[index][‘amount‘]+= Number(query[‘amount‘])    }    else {        cards[index] = req.body;    }    res.send(cards[index]);});

After clicking recharge, the backend will add 100 yuan to the Construction Bank Card, and then return the resource of the Construction Bank Card to the client:

Click the button:

We can see that in card. $ charge ({amount: 100}) in this call, we did not write a callback to change $ scope. card_1, but in the view, card_1 ['amount'] does change because,

Angular automatically fills the return value with card, and card is the $ V attribute value of card_1 (for $ V, check the http://www.cnblogs.com/liulangmao/p/3907307.html), so card_1 in the view will also be updated.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.