[AngularJS] ANGULARJS Series (6) intermediate article of the Ngresource

Source: Internet
Author: User

Directory

    • $http
    • Ngresource

$http is almost all the services that are used in NG development. This section will focus on $http and Ngresource

$http use: $http (config);

Parameters:

Method: A string that requests methods.

URL: string, request address.

Params: A string or object that will be serialized using Paramserializer and as a parameter of a GET request.

Data: A string or an object that acts as the information data for the request.

Headers: An object, string, or function that returns an HTTP request header that is sent to the server. If the return value of the function is null, then headers is not sent. The function accepts a configuration object as a parameter.

Xsrfheadername: String that fills the HTTP request header name of the XSRF token.

Xsrfcookiename: String containing the name of the XSRF token cookie.

Transformrequest: An array of functions/functions. A conversion function or an array that contains a transform function. The conversion function gets the HTTP request body and the request header, and returns their conversion version (usually serialization).

Transformresponse: An array of functions/functions. A conversion function or an array that contains a transform function. The conversion function gets the HTTP response body and the response header, and returns their conversion version (usually serialization).

Paramserializer: A string or a function that returns a string. A function that is used to write the string representation of a request parameter (specified as an object). If the instruction is a string, it will be interpreted as a function registered through $injector, which means that you can create your own serializer by registering the service. The default serialization is $httpparamserializer, or you can use $httpparamserializerjqlike.

Cache:boolean, if True, a default $http cache will be cached as requested, or if there is a cache instance created with $cachefactory, it will be used for caching.

Timeout: number, milliseconds, timeout to abort the request.

Withcredentials:boolean, whether to set the XHR object for Withcredentials flag. See the credentials for more information.

Responsetype: String, response header type.

But usually we do this with the HTTP service in NG.

    Angular.module (' myApp ', []). Controller (' Helloctrl ', [' $http ', function (http) {            var url = '/index.html ';            Http.get (URL)                . Success (function (data, status, headers, config) {                    console.log (' request content: ' + data ')                }). Error (function (data) {                    Console.warn (' request error: ' + data ');        }]);

  

We can also achieve through Ng's promise. 2 results consistent

            Http.get (URL)                . Then (function (RSP) {                    debugger;                    Console.log (' request content: ' + rsp.data ')                , function (RSP) {                    Console.warn (' request error: ' + rsp.data);                });

In Ng, the HTTP service also supports shortcut methods that have

Createshortmethods (' Get ', ' delete ', ' head ', ' Jsonp ')

And

Createshortmethodswithdata (' post ', ' Put ', ' Patch ')

In method Createhttpbackend, the core code for NG HTTP send request is defined.

Configure HTTP
        Angular.module (' myApp ', [], function ($httpProvider) {            //Set AUTH header $ for all requests            httpprovider.defaults.headers.common[' Authorization '] = ' Bearer xx ';            Set do not track for all get requests (get is not in Defaultheaders by default)            $httpProvider. Defaults.headers.get = $ HttpProvider.defaults.headers.get | | {};            $httpProvider. defaults.headers.get[' DNT '] = ' 1 ';        })

Ngresource

If your interface is restful type. Ng is recommended to be handled using the Ngresource method.

Nuget:install-package Angularjs.resource

Define Resource

Let's define 1 Usercard service resources

            . Factory (' Usercard ', [' $resource ', function ($resource) {                return $resource ('/user/:userid/card/:cardid ',                    { Userid:12, CardId: ' @id '},                    {charge: {method: ' Post ', params: {charge:true}, Isarray:false}})            

  

Here's a description of the $resource method

Parameter 1: Must be the URL address for the resource

Parameter 2: Nullable, default value for URL address

Parameter 3: Nullable, Custom Resource method

Call Resource

Start calling the resource we created. (we typically define our resources as services so that other developments can be invoked at any time.)

            . Controller (' Helloctrl ', [' Usercard ', ' $scope ', function (Usercard, $scope) {                var data = Usercard.query ();                $scope. data = data;            }]);

The simplest query method is called (no arguments are required).

But strangely, we don't get the return value in the callback function.

In fact, the Scope.data is assigned an empty reference object first. Then after the data is obtained, it is automatically synchronized to the scope because it is a reference object. The page also refreshes.

If we do something after we get the data. It can also be done by means of a callback function.

                Usercard.query (function (data) {                    //todo                });

The default supported methods and corresponding HttpMethod in Ngresource

{  Get: {Method: ' GET '},Save: {Method: ' POST '}, Query: {:  ' GET ' , IsArray : true}, Remove: {method:   ' DELETE ' }, delete< Span class= "pun" >: {method:   ' DELETE ' }}     

Say the special Save method. (Modify and save the shared Save method in Ngresource)

                Usercard.save ({id:1}, card);//Modify Data                Usercard.save ({}, card); Save data

Of course, we can also create a new method Update method

            . config ([' Resourceprovider ', function ($resourceProvider) {                $resourceProvider. defaults.actions.update = {                    Method: ' PUT '                };            }])

(Get remove delete is relatively simple and does not explain it in detail.)

Add IsArray meaning here, referring to whether the data returned after the method is called is an array or a single JS object. The general Query method is the array.

This address: http://www.cnblogs.com/neverc/p/5920533.html

[AngularJS] ANGULARJS Series (6) intermediate article of the Ngresource

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.