AngularJS $http用法总结

最近由于项目需要,在研究AngularJS $http的用法,查了很多资料,发现貌似没有一篇内容可以完整的满足我对$http的基本了解,为了下次方便自己查找,所以特意把最近查到的一些资料和自己的理解记录下来。如果有理解不到位的地方,也欢迎路过的大神可以指点。
目录

一.$http简介

二.$http的基本语法

三.使用方法举例

四.$http提供的一些快捷请求方式

五.$http.get和$http.post的用法说明

六.$http请求的同步和异步



一.$http简介

1.$http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。

2.$http服务,它是对原生XMLHttpRequest对象的简单封装,是只能接受一个参数的方法,  这个方法会返回一个promise对象,具有sccess和error两个方法。当然,我们也可以在响应返回时用then方法来处理,会得到一个特殊的参数,代表了对象的成功或失败信息,或者可以使用success和error回调代替

二.$http的基本语法

目前$http有两种用法,第一种语法的通用格式如下:

    $http({  
         url:url,           //请求的url路径  
         method:method,     //GET/DELETE/HEAD/JSONP/POST/PUT  
         params:params ,    //转为  ?param1=xx1¶m2=xx2的形式  
         data: data         //包含了将被当做消息体发送给服务器的数据,通常在POST请求时使用  
     }).then(
         function success(resq){  
           //响应成功的处理方法体
         },function error(resq){  
           //响应错误的处理方法体  
         });  

使用then函数来处理$http的回调。其中包括两个函数,success(resp)和error(resp).

success(resp):响应成功时调用,resp是一个响应对象;error(resp):响应失败时调用。

参数说明:

    1.url:请求的路径,是字符串格式
    2.method:请求的类型,如GET,POST,JSONP,DELETE,PUT等方式.最常用的是GET和POST方法,字符串。
    3.params:参数,一般是会被放入请求的URL地址后面一起提交给服务器,如果不是字符串,会被JSON格式化后发送给服务器。
    4.data:发送给服务器的参数,一般在POST请求时,用来传递参数用。是一个对象


其中响应参数resq包含5个参数:

    1.data:响应体,就是后台响应后返回的数据。格式为字符串或对象
    2.status:http返回的状态码,如200,表示服务器响应成功;  
    3.headers(函数):头信息的getter函数,可以接受一个参数,用来获取对应名字的值  
    4.config(对象):生成原始请求的完整设置对象  
    5.statusText:相应的http状态文本,如"ok"  

该方法还有一种等价的写法,如下所示:

    $http({  
         url:url,           //发送请求的url路径  
         method:method,    //取值为GET/DELETE/HEAD/JSONP/POST/PUT,是字符串  
         params:params ,   //转为  ?param1=xx1¶m2=xx2的形式  
         data: data        //包含了将被当做消息体发送给服务器的数据,通常在POST请求时使用  
    }  
    }).success(function(response, status, header, config, statusText){  
     //成功处理  
    }).error(function(data,header,config,status){  
     //错误处理  
    });  

那么这两种方法有什么区别?

then方法的返回值resq相当于一个综合体,而第二种将success,error函数单独写出来的方法,看它的参数就知道,其实就是讲resq的参数进行析构后返回。


三.使用方法举例

1.发送GET请求

     $http({  
           url:"/api/users.json",  
           method:'GET',  
           params:{  
                'username':'jay'
                  }  
      }).success(function (response, status, headers, config) {  
                console.log('response='+response+'status='+status+'headers'+headers+'config='+config);   //如果无法显示,可以采用JSON.stringify(data)进行解析后查看         
         }).error(function (response) {  
      
         }  
     });  

说明:如果发送的参数是多个,则可以采用如下方式来写:

params:{'username':'john','age':27,'phone':'1233232323'}

此处url访问的本地文件,如果跨域访问,可以直接使用完整的url路径。

2.发送POST请求

    $http({
    method : 'POST',
    params : { id:123},
    data:{name:'john',age:27},
    url : "/mypath"}
    ).success(function(response, status, headers, config){  
            //do anything what you want;  
    }).error(function(response, status, headers, config){  
            //do  anything what you want;  
    });

3.带请求头的GET请求

     $http({  
           url:"/api/users.json",  
           method:'GET',  
           params:{'username':'jay'} ,
           headers: {'Content-Type': 'application/x-www-form-urlencoded',
                     'Authentication':'abc'}
      }).success(function (response, status, headers, config) {  
                console.log('response='+response+'status='+status+'headers'+headers+'config='+config);   //如果无法显示,可以采用JSON.stringify(data)进行解析后查看         
         }).error(function (response) {  
      
         }  
     });  

4.带请求头的POST请求

    $http({
    method : 'POST',
    params : { id:123},
    headers: {'Content-Type': 'application/x-www-form-urlencoded',
              'Authentication':'abc'}
    data:{name:'john',age:27},
    url : "/mypath"}
    ).success(function(response, status, headers, config){  
            //do anything what you want;  
    }).error(function(response, status, headers, config){  
            //do  anything what you want;  
    });

四.$http提供的一些快捷请求方式

   $http提供了一些快捷方法让我们使用,一共有六个(其实是六种请求模式)  
   1、$http.get(url,config)  返回HttpPromise对象  
   2、$http.delete(url,config)  返回HttpPromise对象  
   3、$http.head(url,config)  返回HttpPromise对象  
   4、$http.jsonp(url,config)  返回HttpPromise对象  

   5、$http.post(url,data,config) 返回HttpPromise对象

   6、$http.put(url,data,config) 返回HttpPromise对象

  说明:

   url:发送请求的url路径,可以是绝对路径也可以是相对路径(同域情况下可使用相对路径),是字符串类型。

   config:可选的配置项,不是必须的。

   HttpPromise对象: 其实就是响应后返回的结果。我们可以通过console.log来查看它的返回值。

    $http.put('http://baidu.com',{'name':'jhon'}).then(function success(data) {
            // realData被包含在data的“data”字段中,一般它才是我们想要的
            var realData = data.data;
            console.log(realData);
        }, function error(err) {
     
        });

五.$http.get和$http.post的用法说明

1.$http.get的通用格式

     $http.get(url, [config])  
     .success(function(data){})  
     .error(function(data){});  

data的解析方式和参数同第二节中介绍过的resq.或者也可以写成这样:

    $http.get(url,[config]).success(function (response, status, headers, config) {  
             //响应成功处理方法
      }).error(function (response) {  
             //响应成功处理方法  
     });  

2.$http.post的通用格式

     $http.post(url,data,[config])  
      .success(function(result){  
       })  
      .error(function(result){  
       });  

或者这样的形式:

     $http.post(url,data,[config]).success(function (response, status, headers, config) {  
         //响应成功处理方法
       }).error(function (response) {  
          //响应失败处理方法
       });  

get方法和post方法中可选参数config说明:

其实大家可以发现$http.get方法和$http.post方法是等价的,但是在$http(config)中的一些配置参数去哪里了呢,其实就是放在了这里的config中。

config为一个JSON对象,其中主要包含该请求的url、data、method等。

如{url:"login.do",method:"post",data:{name:"12346",pwd:"123"}}。

    method  {String} 请求方式e.g. "GET"."POST"
    url {String} 请求的URL地址
    params {key,value} 请求参数,将在URL上被拼接成?key=value
    data {key,value} 数据,将被放入请求内发送至服务器
    cache {boolean} 若为true,在http GET请求时采用默认的$http cache,否则使用$cacheFactory的实例
    timeout {number} 设置超时时间

那么,在post中的url,data就对应的是config中的url和data,如果想通过这种方式设置params,cache等参数就可以放在config对象中。

返回参数说明:

     data: 返回的数据(或错误)
     status: 响应的状态码,如200表示响应成功
     headers: 一个函数
     congfig: 可查看请求的配置对象

举个例子:

    var postData={name:'john',age:27};
    var config={params:{id:'5',name:'张三丰'},cache:{true},timeout:{1000},headers:{'Content-type':'application/json'}};
    $http.post('postData.php', postData,config)


3.举例

$http.get方法举例:

    $http.get("http://localhost:8080/aosapp/pt/service?formid=pt_aosapp_service_sprintlist&teamid=1")
    .success(function (response) {
          console.log(response);
    })
    .error(function (response) {
         console.log(response);
    }
    );

说明:

在get方法中,没有单独提供可以传递参数的地方,所以如果有参数,请直接在url中进行连接传递即可。同样,url支持绝对路径和相对路径

$http.post方法举例:

    var postData={name:'john',age:27};
    var config={
        params:{id:'5',name:'张三丰'},
        cache:{true},
        timeout:{1000},
        headers:{'Content-type':'application/json'}
    };
    $http.post('postData.php', postData,config).success(function (response) {
          console.log(response);
    })
    .error(function (response) {
         console.log(response);
    }
    );

4.$http.get和$http.post方法的对比

$http.post接收三个参数,$http.get接收两个参数,$http.post比$http.get多了一个“请求发送的数据”,$http.get的请求参数可以放在url中进行发送,也可以在配置项config中设置params来传递。“

请求配置的参数”是一个嵌套的json对象必须是 {params: json对象}。

后端接收get和post参数的区别:

    “请求发送的数据”是一个json对象,在后端应该用req.body接收,一般用于接收post发送过来的参数;
     "请求配置的参数"在后端应该用req.query接收,一般用于接收get方法传递的参数。

5.在$http.get和在$http.post中添加请求头

  通过在config中直接设置,设置方式前面举例里面有设计,请参考前面第五节第2小节的举例说明。

六.$http请求的同步和异步

$http发送请求是异步操作,但是在一些业务场景中,也需要进行同步请求。

采用Angular提供的$q可以实现同步请求。

$q采用的是promise/A规范,Promise是一种模式,以同步操作的流程形式来操作异步事件,避免了层层嵌套,可以链式操作异步事件。

具体的实现过程比较长,解说也比较多,在这里贴个链接,大家可以自行查看。

实现同步请求的方式


---------------------
版权声明:本文为CSDN博主「心若向阳无谓悲伤」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_31490071/article/details/80704224

原文地址:https://www.cnblogs.com/qqhfeng/p/11347200.html