当响应准备就绪时,我应该关注带有$ http调用的AngularJS工厂吗?

时间:2013-01-10 15:09:52

标签: http callback angularjs

我在内部使用$ http调用类似的工厂,如下所示:

appModule = angular.module('appModule', []);

appModule.factory('Search', function($rootScope, $http) {
  var Search;
  Search = {};
  Search.types: ["bacon"];
  Search.pastEvents = null;
  $http.get('api/highlights').success(function(response) {
    return Search.pastEvents = response.data;
  });
  return Search;
});

var notes_module = angular.module('notes', []);

notes_module.config(['$routeProvider', function ($routeProvider) {

  var notes_promise = ['Notes', '$route', 'Search', function (Notes, $route, Search) {
    //suspect that Search not having pastEvents ready in time of calling index method
    //Notes resource  
    return Notes.index({subject_id: 1 }, Search);    
  }];

  $routeProvider.when('/notes', {
    templateUrl:'index.tpl.html',
    controller:'NotesCtrl',
    resolve:{
      notes: notes_promise,
    }
  });

}]);

我应该关心来自$ http调用的数据何时准备好以及何时初始化/注入此工厂? pastEvents会准备好吗?如果我应该关心我该怎么做?

我怀疑Search对象在调用Notes资源的索引方法时没有准备好pastEvents。

1 个答案:

答案 0 :(得分:5)

取决于:

如果您立即放入$scope进行使用,例如在ng-repeat中,然后是。

如果您需要控制器中的其他功能,那么是。例如。如果您在控制器上的过滤功能中使用pastEvents。在这种情况下,最好将所有操作保留在服务内部,并使用$q来解决异步问题。

(这只是一个例子)

appModule.factory('sharedApplication', function($rootScope, $http, $q) {
  var deferred = $q.defer();

  $rootScope.$on('data:loaded', function(e, data) {
    deferred.resolve(data);
  });

  return {
     getApp: function(filter) {
        if (!filter) { filter = function() { return true; } }

        var filtered = {};
        deferred.promise.then(function(data) {
           filtered.pastEvents = _.filter(data, filter); 
        };
        return filtered;
     }
  };
});

一点解释。数据随服务中的事件一起到达。此时getApp()可能已被调用。但这并不重要,因为$q将确保数据仅在以后到达时进行过滤。控制器不需要知道,只要它不尝试执行以下操作:

$scope.app = service.getApp();
for(var i = 0; i < $scope.app.pastEvents.length; i++) {
   ...
} 

如果您确实需要评估控制器中的内容,请使用$scope.$watch(),例如:

$scope.$watch('app', function(value) {
   ...
}, true);

修改

在我看来,在您Search中使用$routeProvider时,Notes.index({subject_id: 1 }, Search) 尚未得到解决:

Search

因此,请尝试解决Notes并在您的控制器中使用您的Search资源。

您需要在appModule.factory('Search', function($rootScope, $http, $q) { var deferred = $q.defer(); $http.get('api/highlights').success(function(response) { deferred.resolve({ type: ["bacon"], pastEvents: response.data)}; }); return deferred.promise; }); 服务中退回承诺。两个选项:

  • 返回$ http承诺,但这可能不是你想要的,如果你需要先对数据做些什么
  • 使用$ q并返回其承诺

$ q示例:

{{1}}