$http服务应用

2017-05-25  本文已影响0人  RelaxedAndHappy

$http服务的使用场景:

var promise = $http({
    method: "post",//发送请求的方式,get,post,put,delete,head,jsop;常用get post
    url: "data.json", //请求的地址
    params: {"name": "lisa"},//传递参数,转换name=lisa的形式跟在请求路径的后面
    data:blod//通常是在发送post请求时使用,
}).success(function(data) {
    console.log("响应成功");
}).error(function() {
   console.log("响应失败");
})

then()函数:可以用来处理$http服务的回调,then()函数接受两个可选的函数作为参数,表示sucees或者error状态的处理,也可以使用success和error回调代替;then(successFn,errFn,nontifyFn),无论promise成功还是失败了,then都会立刻异步调用successFn或者errFn.这个方法始终用一个参数来调用回调函数,

promise.then(function(response) {
    //响应成功时调用,response是一个响应对象;
},function(response) {
    //响应失败时调用,resp带有错误信息
});

then()函数接受response响应对象包含5个属性:

prmoise.success(function(data, status, headers, config) {
   // 处理成功的响应
});
prmoise.error(function(data, status, headers, config) {
    //处理非成功的响应
})

示例:

//html
<body ng-app="myApp" ng-controller="myCtrl" ng-init="loadData()">
    <table>
        <thead>
            <tr>
                <th>名称</th>
                <th>属性</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="data in myData">
                <td>{{data.name}}</td>
                <td>{{data.attr}}</td>
            </tr>
        </tbody>
    </table>
</body>

success和error的方法

  var app = angular.module("myApp",[]);
        app.controller("myCtrl", function($scope, $http) {
            $http({
                method: "get",
                url: "data.json"  
            }).success(function(data, herders, status, config) {
                console.log(data);
                $scope.myData = data;
            }).error(function(data, herders, status, config) {
            console.log(data)
             })
})

then()方法来处理$http服务的回调;

var app = angular.module("myApp", []);
      app.controller("myCtrl", function($scope, $http) {
        $http.get("data.json").then(function(response) {
          $scope.myData = response.data//
        },function(response) {
          console.log(response.statusText);
        })
});
上一篇 下一篇

猜你喜欢

热点阅读