Using $resource in Angularjs

Source: Internet
Author: User
Tags representational state transfer

This service can create a resource object that we can easily interact with to support restful service-side data sources, and it comes in handy when working with a restful data model.
Rest is an abbreviation for the representational state Transfer, which is a way for the server to intelligently provide data services

1) We first need to introduce the Ng-resource module, after angular

<script src= "Js/vendor/angular.js" ></script>

<script src= "Js/vendor/angular-resource.js" ></script>


2) We need to refer to it as a dependency in our application
Angular.module (' myApp ', [' Ngresource ']);

3) How to use?
The $resource service itself is a factory that creates a resource object, and the returned $resource object contains a high-level API for interacting with the backend server.

var user= $resource ('/api/users/:userid ', {userId: ' @id '});

The user object can be understood as an interface that interacts with a restful backend service.


First, HTTP get type method

①get Request: Get (PARAMS,SUCCESSFN,ERRRORFN)

A get () request is typically used to obtain a single resource without defining a specific parameter.


Get/api/users
User.get (function (RESP) {
Processing success

},function (Err) {
Handling Errors

});

If a named parameter is passed in the parameter (the parameter in our example is an ID), then the Get () method sends the request to the URL that contains the ID:
Initiate a request: get-->/api/users/123
User.get ({id: ' 1234 '},function (RESP) {
Success
},function (Error) {
Fail
});

②query Request: QUERY sends a GET request to the specified URL and expects to return a collection of resource objects in JSON format.
Initiate a request
User.query (function (users) {
Reads the first user in a collection
var user=users[0];
});

the only difference between the query () and get () methods is that ANGULARJS expects the query () method to return an array.


Ii. Methods for non-HTTP GET types
1. Save (params, payload, SUCCESSFN, ERRORFN)
The Save method sends a POST request to the specified URL and uses the data body to generate the request body. The Save () method is used to generate a new resource on the server. Payload: Represents the data volume sent by the request

Send a request with the body {name: ' Ari '}

User.save ({},{name: ' Ari '},function (resp) {

},function (Error) {

});

2. Delete (params, payload, SUCCESSFN, ERRORFN)
The Delete method sends a delete request to the specified URL and uses the data body to generate the request body. It is used to delete an instance on the server:

Delete/api/users
User.delete ({}, {
ID: ' 123 '
}, function (response) {
Handling a successful Delete response
}, function (response) {
Handling a non-successful delete response
});

3. Remove (params, payload, SUCCESSFN, ERRORFN)
The Remove method and the Delete () method work exactly the same, meaning that the delete is a reserved word for JavaScript and will cause additional problems in IE.

//Initiate a request:
Delete/api/users
User.remove ({}, {
ID: ' 123 '
}, function (response) {
//Processing a successful delete response
}, function (response) {
//handling a non-successful delete response
});


Extended $resource

third, $resource set the object

$resource encapsulation of five common requests, we can also extend the $resource to extend $resource we need to pass in the third parameter, which is an object.

$resource ('/api/users ', {},{  sendemail:{    method: ',    URL: ',    params:{},    Isarray:boolean,    transformrequest: Function or function array    transformresponse: function or function array    cache: Boolean or Cache object    timeout: Numeric or Promise Object    withcredentials: Boolean type    Responsetype: string, used to set Xmlhttprequestresponsetype property  }})

Iv. Custom $resource Services

We can also use $resource services as a basis for custom services.

Angular.module (' testApp ', [' Ngresource ']), factory (' UserService ', [' $resource ', function ($resource) {

Return $resource (url,{},{});

}]);

Example:


v. Application examples in the project

Define ([' {angular}/angular ', ' {angular-sanitize}/angular-sanitize ', ' {w20-ui}/modules/select '], function (Angula    R) {' Use strict ';    var hubcomponentimport = angular.module (' Hubcomponentimport ', [' ui.select ', ' ngsanitize ']); Hubcomponentimport.controller (' Hubimportcomponentctrl ', [' $scope ', ' $routeParams ', ' $timeout ', ' $resource ', ' $            Location ', function ($scope, $routeParams, $timeout, $resource, $location) {$scope. editcomponent = function () {            Initialize parameter $scope. component= {tags:[]}; Use $resource to customize the Post method var components= $resource (' Rest/components/url ', {},{getcomponent: {metho            D: ' POST '}});                Receive the page input data and send the request var component= components.getcomponent ({},{url: $scope. Componenturl},function (data) {            $scope. Component = data;            });        Turn to edit.html page $scope. searchcomponent = ' manage/views/edit.html ';                   };    }]);   return {     Angularmodules: [' Hubcomponentimport '};}); 







Using $resource in Angularjs

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.