Angularjs的http请求

1、使用$http发起请求:

$scope.exportWord = function (item) {

        var config = {

          headers: {

            'Content-Type': 'application/json'

          }};

        $http.post(commonFileUrl + "/paperwordreport/poverty_export_word", item, config)

          .then(function (result) { //正确请求成功时处理

            $scope.downloadExportWord(result.data);

          }).catch(function (result) { //捕捉错误处理

            console.log(result);

          }); }

2、使用Restangular发起http请求:

(1)Restangular在使用前需要设置请求的基地址,即beseUrl:

         RestangularProvider.setBaseUrl(commonUrl);

(2)Restangular的all与one的区别

app.controller("myCtrl",function($scope,Restangular){
    //get请求
    Restangular.all("get").get({}).then(function(data){
        console.log(JSON.stringify(data));//[{"name":"张飞111"},{"name":"关羽111"}]
  })
    Restangular.all("get",147).get({}).then(function(data){
        console.log(JSON.stringify(data));//[{"name":"张飞111"},{"name":"关羽111"}]
    })
    Restangular.one("get",123).get({}).then(function(data){
        console.log(JSON.stringify(data));//[{"name":"刘备"},{"name":"曹操"}]
  })

    //post请求
    Restangular.all("post").post().then(function(data){
        console.log(JSON.stringify(data));//[{"age":"27"}]
   })
    Restangular.one("post",456).post().then(function(data){
        console.log(JSON.stringify(data));//[{"age":"29"}]
    })
})

总结:

  ①、Restangular的All方法会让所有的HTTP请求将首个字符串作为路径来请求数据,第二个字符串将不起作用。例如Restangular.all("get",147)请求路径实际还是'/get'

  ②、Restangular的One方法通过单个对象来发送嵌套的请求,路径按参数顺序用"/"分隔,例如Restangular.one("get",123)请求路径就是'/get/123'

  ③、Restangular是get请求还是post请求与all或one方法无关,与all或one方法后的get或post方法有关。

  ④、Restangular.all("get").get("")就是get请求,get方法内传的是请求的对象,对应的是url?后的参数值,如{"name":"lily"}则表示get请求的url为xxx?name=lily,如果是空对象,就表示不传参,如果不传对象,传字符串,Restangular会自动分隔解析成对象的形式。例如get("555"),会被解析成{"0":5,"1":5,"2":5}。如果不传参数,也会被解析成传的空对象。

  ⑤、Restangular.all("post").post()是post请求。


版权声明:本文为m0_52941727原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>