小编典典

在服务中处理$ http响应

angularjs

我最近公布的我面对这个问题的详细说明,这里的SO。由于我无法发送实际的$http请求,因此我使用了超时来模拟异步行为。在@Gloopy的帮助下,从模型到视图的数据绑定工作正常

现在,当我使用$http而不是$timeout(在本地测试)时,我可以看到异步请求成功,并且data在我的服务中充满了json响应。但是,我的看法没有更新。

在这里更新了Plunkr


阅读 320

收藏
2020-07-04

共1个答案

小编典典

这是一个可以满足您需求的Plunk:http
://plnkr.co/edit/TTlbSv?p=preview

这个想法是您直接使用promise和它们的“ 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 has a then function, 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', function( myService,$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;
    });
  };
});
2020-07-04