Use of asynchronous request $ http object in AngularJS
??
AngularJS provides$. Ajax similar to jqueryFor asynchronous requests.
AngularJS is highly admired for asynchronous operations, so$ Http operations are asynchronous, unlike the async parameter provided in jquery. ajax.
For$ Summary and use of http objects.
Usage:
$ Http (config );
Parameters:
Config)
Config |
Object |
Object describing the request to be made and how it shocould be processed. The object has following properties:
- Method-
{string} -HTTP method (e.g. 'get', 'post', etc) ---------------- http interaction method: GET/POST
- Url-
{string} -Absolute or relative URL of the resource that is being requested. ---------------- URL transfer address
- Params-
{Object. } -Map of strings or objects which will be serialized withparamSerializer And appended as GET parameters. ------------------ Map-type parameter, transmitted to the background
- Data-
{string|Object} -Data to be sent as the request message data. ------------------ required parameters
- Headers-
{Object} -Map of strings or functions which return strings representing HTTP headers to send to the server. if the return value of a function is null, the header will not be sent. functions accept a config object as an argument.
- XsrfHeaderName-
{string} -Name of HTTP header to populate with the XSRF token.
- XsrfCookieName-
{string} -Name of cookie containing the XSRF token.
- TransformRequest-
{function(data, headersGetter)|Array. } -Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. See Overriding the Default Transformations
- TransformResponse-
{function(data, headersGetter, status)|Array. } -Transform function or an array of such functions. The transform function takes the http response body, headers and status and returns its transformed (typically deserialized) version. See Overriding the Default TransformationjqLiks
- ParamSerializer-
{string|function(Object ):string} -A function used to prepare the string representation of request parameters (specified as an object ). if specified as string, it is interpreted as function registered with the $ injector, which means you can create your own serializer by registering it as a service. the default serializer is the $ httpParamSerializer; alternatively, you can use the $ httpParamSerializerJQLike
- Cache-
{boolean|Cache} -If true, a default $ http cache will be used to cache the GET request, otherwise if a cache instance built with $ cacheFactory, this cache will be used for caching. ------------------ cache. When it is set to true, the default $ HTTP cache will be used to cache GET requests. Otherwise, the Factory cache instance will be created.
- Timeout-
{number|Promise} -Timeout in milliseconds, or promise that shocould abort the request when resolved.
- WithCredentials-
{boolean} -Whether to setwithCredentials Flag on the XHR object. See requests with credentials for more information.
- ResponseType-
{string} -See XMLHttpRequest. responseType.
|
Return: An httpPromise object (generally only data and status are used)
HttpPromise |
Returns a promise object with the standardthen Method and two http specific methods:success Anderror .then Method takes two arguments a success and an error callback which will be called with a response object.success Anderror Methods take a single argument-a function that will be called when the request succeeds or fails respectively. The arguments passed into these functions are destructured representation of the response object passed intothen Method. The response object has these properties:
- Data-
{string|Object} -The response body transformed with the transform functions. ------------------ returned data
- Status-
{number} -HTTP status code of the response. ------------------ returned status. If the value is equal to 200, the operation is successful. Otherwise, the operation fails.
- Headers-
{function([headerName])} -Header getter function.
- Config-
{Object} -The configuration object that was used to generate the request. ---------------- is used to generate The configuration object of the request, The original input parameters, and so on.
- StatusText-
{string} -HTTP status text of the response. ------------------ returned status text
|
Method:
Get (url, [config]); a quick way to execute GET requests.
Post (url, data, [config]); a quick way to execute POST requests.
Put (url, data, [config]);
Patch (url, data, [config]);
Jsonp (url, [config]);
Head (url, [config]);
Delete (url, [config]);
My own example (use promise to solve the callback hell problem)
var deferred = $q.defer(); $http({ cache: false, method: 'GET', url: Constants.baseURL + '/loginj', params: params, headers: {'X-Auth-Token': $window.token} }).then(function(res) { if (200 === res.status && res.data.LoginResponse.success) { if (!Array.isArray(res.data.LoginResponse.settings.account)) { res.data.LoginResponse.settings.account = [res.data.LoginResponse.settings.account]; } CurrentUser.id = res.data.LoginResponse.settings.id; deferred.resolve(res.data.LoginResponse.settings); } else { deferred.reject(failed to fetch login data); } }, function(error) { deferred.reject(error.status+ +error.statusText); }); return deferred.promise;