angular中的$http服务

$http是ng内置的一个服务。是简单的封装了浏览器原生的XMLHttpRequest对象。

写法1

    $http({
      method: "GET",
      url: 'data.json',
    }).success(function(data, status, headers, config){
      $scope.list = data;
    }).error(function(data, status, headers, config) { 
        //
    });
实际上$http方法返回一个promise对象,这样可以方便的进行链式调用。
于是我们可以这样
var promise = $http({
      method: "GET",
      url: 'data.json',
 })
promise
    .success(function(data, status, headers, config){
        // $scope.list = data;
    })
    .error(function(data, status, headers, config) { 
        //
    });
注意:
1. 如果响应状态码在200和299之间,会认为响应是成功的,success回调会被调用,否则会调用error回调。
2. 如果响应结果是重定向,XMLHttpRequest会跟进这个重定向,并不会调用error回调。
 
写法2
使用promise对象的then方法
then()方法与其他两种方法的主要区别是,它会接收到完整的响应对象,而success()和error()则会对响应对象进行析构。个人理解是拆分了
注意:推荐用then和catch分别代表成功和失败,不要用success和failed。因为好像1.6以后success已被弃用,为了和标准的promise保持一致。
   $http({
        method: "GET",
        url: 'data.json'
    })
    .then(successCallback, errorCallback);
function successCallback(responseObj){ //相应对象变了,不是data, status, headers, config而是包含他们四个属性的完整对象 $scope.list = responseObj.data } function errorCallback(){ }
 
写法3  快捷写法
jQuery源码中,$.get(url,data,fn),$.post等是对$ajax的再次封装。ng类似。
 $http.get('data.json').success(function(data){
      $scope.list = data
 })

实例:demo

原文地址:https://www.cnblogs.com/mafeifan/p/5039798.html