angularjs – 处理$http响应服务

前端之家收集整理的这篇文章主要介绍了angularjs – 处理$http响应服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我最近发布了一个详细的描述我面临的问题 here在SO。由于我不能发送实际的$ http请求,我使用超时模拟异步行为。从我的模型到视图的数据绑定工作正常,借助@Gloopy

现在,当我使用$ http而不是$ timeout(本地测试)时,我可以看到异步请求成功,数据在我的服务中用json响应填充。但是,我的观点不是更新。

更新Plunkr here

这是一个Plunk,做你想要的: http://plnkr.co/edit/TTlbSv?p=preview

这个想法是,你直接使用promises和他们的“then”函数来操作和访问异步返回的响应。

app.factory('myService',function($http) {
  var myService = {
    async: function() {
      // $http returns a promise,which has a then function,which also returns a promise
      var promise = $http.get('test.json').then(function (response) {
        // The then function here is an opportunity to modify the response
        console.log(response);
        // The return value gets picked up by the then in the controller.
        return response.data;
      });
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});

app.controller('MainCtrl',function( myService,$scope) {
  // Call the async method and then do stuff with what is returned inside our own then function
  myService.async().then(function(d) {
    $scope.data = d;
  });
});

这里是一个稍微复杂的版本,缓存请求,所以你只有第一次(http://plnkr.co/edit/2yH1F4IMZlMS8QsV9rHv?p=preview):

app.factory('myService',function($http) {
  var promise;
  var myService = {
    async: function() {
      if ( !promise ) {
        // $http returns a promise,which also returns a promise
        promise = $http.get('test.json').then(function (response) {
          // The then function here is an opportunity to modify the response
          console.log(response);
          // The return value gets picked up by the then in the controller.
          return response.data;
        });
      }
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});

app.controller('MainCtrl',$scope) {
  $scope.clearData = function() {
    $scope.data = {};
  };
  $scope.getData = function() {
    // Call the async method and then do stuff with what is returned inside our own then function
    myService.async().then(function(d) {
      $scope.data = d;
    });
  };
});

猜你在找的Angularjs相关文章