ANGULARJS interacting with servers (4)

Source: Internet
Author: User

Transferred from: http://itindex.net/detail/50919-angularjs-%E6%9C%8D%E5%8A%A1%E5%99%A8-%E4%BA%A4%E4%BA%92

For AJAX applications (using xmlhttprequests), the traditional way to request a server is to get a reference to a XMLHttpRequest object, initiate a request, read the response, check the status code, and finally handle the response from the service side. An example of the entire process is as follows:

var xmlhttp = new XMLHttpRequest (); xmlhttp.onreadystatechange = function () {    if (xmlhttp.readystate = = 4 && XM Lhttp.status = =) {        var response = Xmlhttp.responsetext;    } else if (xmlhttp.status = = 400) {//or can be any status code starting with 4        //gracefully handling error    }};//establishing connection Xmlhttp.open ("GET", "http://myserver/ API ", true);//Initiate request xmlhttp.send ();

This is a cumbersome task for simple, common, and often repetitive tasks. If you want to reuse the above process, you should either encapsulate or use a code base.

The AngularJS XHR API complies with an interface that is commonly referred to as promise. Because XHR is a method called asynchronously, the response of the server is returned at an indeterminate point in the future (we want it to return immediately). The Promise interface provides a way to handle this response and allows the user of the promise to use it in a predictable way.

For example, we want to get a user's information from the server, assuming that the backend interface used to accept the request is located on the/api/user path, and that the interface can accept an id attribute as a URL parameter, then an example of how to initiate a XHR request using Angular's core $http service is as follows:

$http. Get (' Api/user ', {params: {id: ' 5 '}}). Success (function (data, status, headers, config) {    //do something after the load succeeds}). Error (Function (data, status, headers, config) {    //Handle error});

If you are a jquery user, you should find that Angularjs and jquery are very similar in terms of handling asynchronous requests.

The $http.get method used in the example above is one of the many shortcut methods provided by Angularjs's core service $http. Similarly, if you want to use ANGULARJS to send a POST request to the same URL with some post data, you can do the following:

var postdata = {text: ' Long blob of text '};//the following line will be appended to the URL as a parameter, so the POST request will eventually become/api/user?id=5var config = {params: {id: ' 5 ' }}; $http. Post (' Api/user ', PostData, config). Success (function (data, status, headers, config) {    //do something after success}). Error (function (data, status, headers, config) {    //Handling error});

For most common request types, there are similar shortcut methods, such as, POST, DELETE, PUT, JSONP.

I. Further configuration requests

Although the standard request method is relatively simple to use, there are sometimes drawbacks to poor configuration. If you want to achieve these things you will encounter difficulties:

A. Add some authorization headers to the request.

B. Modify how the cache is processed.

C. Change the sent request in some special way, or transform the received response.

In these cases, you can configure the request in depth by passing an optional configuration object to the request. In the previous example, we used the Config object to specify an optional URL parameter. But the get and post methods there are some shortcuts. This deep simplification of the method invocation example is as follows:

$http (config)

The following is a basic pseudo-code template that is used to invoke the previous method:

$http ({   method:string,   url:string,   params:object,   data:string or object,   Headers:object,   transformrequest:function transform (data, headersgetter) or an array of functions,   Transformresponse: function transform (data, headersgetter) or an array of functions,   Cache:boolean or Cache object,   Timeout:numbe R,   Withcredentials:boolean});

GET, Post, and other shortcut methods automatically set the method parameter, so you do not need to set it manually. The Config object is passed as the last parameter to $http.get and $http.post, so this parameter can be used inside all the shortcut methods. You can pass the Config object to modify the sent request, and the Config object can set the following key values.

Method: A string that represents the type of the HTTP request, such as Get or post.

A Url:url string that represents the absolute or relative resource path of the request.

Params: An object with a key and a value that is a string (exactly a map) that represents the key and value that needs to be converted to a URL parameter. For example:

[{key1: ' value1 ', Key2: ' value2 '}]

will be converted into

? key1=value&key2=value2

and will be appended to the URL. If we use a JS object (instead of a string or a value) as the value in the map, the JS object is converted to a JSON string.

Data: A string or object that will be sent as request data.

Timeout: The number of milliseconds to wait before the request times out.

Two. Set the HTTP header

Angularjs comes with some default request headers, and all requests made by angular will have these default request header information. The default request header consists of the following two:

1.accept:appliction/json,text/pain,/

2.x-requested-with:xmlhttprequest

If you want to set a special request header, it can be implemented in the following two ways.

First, if you want to set the request header to every request sent out, you can set the special request header you want to use as the default value for Angularjs. These values can be set through the $httpprovider.defaults.headers configuration object, which is usually done in the configuration section of the app. So, if you want to use the "Do Not track" header for all get requests and delete the Requested-with header for all requests, you can simply do the following:

Angular.module (' MyApp ', []).    Config (function ($httpProvider) {        //delete angularjs default X-request-with header        Delete $ httpprovider.default.headers.common[' X-requested-with '];        Set does not track $httpProvider for all get requests        . default.headers.get[' DNT '] = ' 1 ';});

If you only want to set the request headers for certain requests, but do not use them as default values, you can pass the header information to the $http service as part of the configuration object. Similarly, custom header information can be passed as part of the second parameter to a GET request, and the second parameter can accept the URL parameter at the same time.

$http. Get (' Api/user ', {     //Set Authorization (authorization) header. In a real application, you need to go to a service to get the Auth token     headers: {' Authorization ': ' Basic Qzsda231231 '},     params: {id:5}}). Success ( function () {//handle successful case});

Three. Cache response

For HTTP GET requests, ANGULARJS provides a simple, out-of-the-box caching mechanism. It is not available by default for all request types, and in order to enable caching, you need to do some configuration:

$http. Get (' Http://server/myapi ', {    cache:true}). Success (function () {//Handling success});

This allows caching to be enabled, and then ANGULARJS will cache the response from the server. The next time a request is sent to the same URL, Angularjs will return the response content in the cache. The cache is also intelligent, so even if you send multiple mock requests to the same URL, the cache will only send a request to the server, and after receiving a response from the service, the contents of the response will be distributed to all requests.

However, this is somewhat less practical because the user sees the old cached results and then sees the new results popping up. For example, when a user is about to click on a piece of data, it may suddenly change.

Note that, in essence, the response (even if it is read from the cache) is still asynchronous. In other words, the first time you make a request, you should encode it in a way that handles the asynchronous request.

Four. Conversion requests and responses

For all requests made through the $http service and the responses received, ANGULARJS will perform some basic conversions, including the following.

1. Conversion requests

If the requested configuration object property contains a JS object, then the object is serialized into JSON format.

2. Conversion response

If the XSRF (cross site request forgery abbreviation, which is a method of cross-site scripting attack) is detected as a prefix, it is discarded directly. If a JSON response is detected, the JSON parser is used to deserialize it.

If you do not need some of these transformations, or if you want to self-convert, you can pass in your own function inside the configuration item. These functions get the request/response body of the HTTP and the protocol header information, and then output the serialized, modified version. These conversion functions can be configured using Transformlrequest and transformresponse as keys, and these functions are configured with the $httpprovider service in the config function of the module.

When do we need to use these things? Let's say we have a service that's better suited to work in a jquery way. The post data uses the form Key1=val1&key2=val2 (that is, a string) instead of the {key1:val1, Key2:val2}json format. We can do this in every request, or we can add a standalone transformrequest call, for the current example, we're going to add a generic transformrequest, This translates from JSON to string for all requests that are made. Here's how it's implemented:

var module = angular.module (' myApp '); Module.config (function ($httpProvider) {    $ HttpProvider.defaults.transformRequest = function (data) {          ////Use jquery's Param method to convert the JSON data to a string form          return $.param (data);     };});

ANGULARJS interacting with servers (4)

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.