处理$http服务中的响应

2022-08-30 00:50:19

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

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

更新了Plunkr在这里


答案 1

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

这个想法是,你直接使用承诺及其“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;
    });
  };
});

答案 2

让它变得简单。就像

  1. 在您的服务中返回(无需在服务中使用)promisethen
  2. 在控制器中使用then

演示。http://plnkr.co/edit/cbdG5p?p=preview

var app = angular.module('plunker', []);

app.factory('myService', function($http) {
  return {
    async: function() {
      return $http.get('test.json');  //1. this returns promise
    }
  };
});

app.controller('MainCtrl', function( myService,$scope) {
  myService.async().then(function(d) { //2. so you can use .then()
    $scope.data = d;
  });
});