AngularJS 中 异步请求$http 对象的使用



AngularJS 提供了一个类似jquery的$.ajax的对象,用于异步请求。

在AngularJS中对异步操作是推崇至极的,所以$http的操作都是异步的不像jquery.ajax里还提供了async参数。

对于官网的$http对象的总结和使用。

用法:

$http(config);

参数:

config (常用的参数标红,翻译了一下)

config object
Object describing the request to be made and how it should be processed. The object has following properties:

  • method – {string} –
    HTTP method (e.g. ‘GET‘, ‘POST‘, etc)  ------------------  http交互方法:GET/POST 两种
  • url – {string} –
    Absolute or relative URL of the resource that is being requested.
    ------------------  URL传输地址
  • params – {Object.<string|Object>} –
    Map of strings or objects which will be serialized with theparamSerializer and
    appended as GET parameters.    ------------------  Map 类型的参数,传输给后台
  • data – {string|Object} –
    Data to be sent as the request message data. ------------------  要求传入的参数
  • 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.<function(data, headersGetter)>} –
    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.<function(data, headersGetter, status)>} –
    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,string>):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. ------------------  缓存,设为true的时候,默认的$ HTTP缓存将用于缓存GET请求,否则,创建Factory缓存实例.
  • timeout – {number|Promise} –
    timeout in milliseconds, or promise that should abort the request when resolved.
  • withCredentials - {boolean} -
    whether to set the withCredentials flag
    on the XHR object. See requests with credentials for
    more information.
  • responseType - {string} -
    see XMLHttpRequest.responseType.

返回: 一个httpPromise对象(一般只用data和status)

HttpPromise
Returns a promise object with the standard then method
and two http specific methods: success and error.
Thethen method
takes two arguments a success and an error callback which will be called with a response object. Thesuccess and error 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 into the then method.
The response object has these properties:

  • data – {string|Object} –
    The response body transformed with the transform functions. 
    ------------------  返回数据
  • status – {number} –
    HTTP status code of the response. ------------------  返回状态。等于200时为成功,否则失败。
  • headers – {function([headerName])} –
    Header getter function.
  • config – {Object} –
    The configuration object that was used to generate the request. 
    ------------------  用于生成请求的配置对象,原来传入的参数等。
  • statusText – {string} –
    HTTP status text of the response. ------------------  返回的状态文本

方法:

get(url, [config]);        
快捷的方法来执行GET请求。

post(url, data, [config]); 
快捷的方法来执行POST请求。

put(url, data, [config]);

patch(url, data, [config]);

jsonp(url, [config]);

head(url, [config]);

delete(url, [config]);

我自己的使用例子(使用promise解决回调地狱问题)

          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;

官网地址:https://docs.angularjs.org/api/ng/service/$http (需要翻墙)

参考文章:http://zhaoyanblog.com/archives/99.html

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-13 12:14:46

AngularJS 中 异步请求$http 对象的使用的相关文章

angularjs中directive声明scope对象时修饰符解释和用法

在angular中我们定义directive方法时,可以看到 return { restrict: 'AE', scope: {}, template: '<div></div>', link: function() {} } 除了代码中出现的属性,还有一些其他的属性可供配置,这里不作详述. 今天我们要说的重点是scope字段. 常规用法设置 scope: { name: '=', age: '=', sex: '@', say: '&' } 假设我们的hml代码如下 &l

angularjs $q、$http 处理多个异步请求

在实际业务中经常需要等待几个请求完成后再进行下一步操作.但angularjs中$http不支持同步的请求. 解决方法一: $http.get('url1').success(function (d1) { $http.get('url2').success(function (d2) { //处理逻辑 }); }); 解决方法二: then中的方法会按顺序执行. var app = angular.module('app',[]); app.controller('promiseControl'

AngularJs中POST和GET方式的ajax请求

angular中ajax请求的方法说明: /* * _http:angularJs中的$http对象 * _url:ajax请求的URL * _method:请求方式:POST或GET * _params:GET方式请求时传递的参数 * _data:POST方式请求时传递的参数 * _responseType:在请求中设置XMLHttpRequestResponseType属性,""(字符串,默认), * "arraybuffer"(ArrayBuffer);&qu

Servlet3.0中的异步请求

package com.itheima.async; import java.io.IOException; import javax.servlet.AsyncContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; i

ios中的ASIHTTPRequest的同步请求和异步请求

1.首先加入ASI开源库 2. WebImageView.h #import <UIKit/UIKit.h> #import "ASIHTTPRequest.h" @interface WebImageView :UIImageView<ASIHTTPRequestDelegate> - (void)setImageURL:(NSURL *)url; @end WebImageView.m #import "WebImageView.h" #

黄聪:AngularJS中的$resource使用与Restful资源交互(转)

原文:http://blog.csdn.net/he90227/article/details/50525836 1.AngularJS中的 $resource 这个服务可以创建一个资源对象,我们可以用它非常方便地同支持RESTful的服务端数据源进行交互,当同支持RESTful的数据模型一起工作时,它就派上用场了.      REST是Representational State Transfer(表征状态转移)的缩写,是服务器用来智能化地提供数据服务的一种方式 1)我们首先需要引入ng-Re

AngularJS中实现无限级联动菜单(使用demo)

原文地址:http://www.cnblogs.com/front-end-ralph/p/5133122.html 昨天没来得及贴几个使用demo,今天补上,供有兴趣的同学参考 :) 1. 同步加载子选项demo2. 异步加载子选项demo3. 初始值回填demo4. 倒金字塔依赖demo directive的源代码请移步上一个帖子:http://www.cnblogs.com/front-end-ralph/p/5131687.html 1. 同步加载子选项在各联动菜单加载之前,我们已经通过

手动封装js原生XMLHttprequest异步请求

Code Object.extend =function(targetObj,fnJson){ //扩展方法,类似于jQuery的$.extend,可以扩展类的方法,也可以合并对象 for(var fnName in fnJson){ targetObj[fnName]=fnJson[fnName]; } return targetObj; }; HttpAjax = (function(){ function HttpAjax(options){ var settings={ type:'po

AngularJS 中的Promise --- $q服务详解

    阅读目录 什么是Promise $q服务 先说说什么是Promise,什么是$q吧.Promise是一种异步处理模式,有很多的实现方式,比如著名的Kris Kwal's Q还有JQuery的Deffered. 回到顶部 什么是Promise 以前了解过Ajax的都能体会到回调的痛苦,同步的代码很容易调试,但是异步回调的代码,会让开发者陷入泥潭,无法跟踪,比如: funA(arg1,arg2,function(){ funcB(arg1,arg2,function(){ funcC(arg