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

Jak*_*har 4 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,
    }
  });

}]);
Run Code Online (Sandbox Code Playgroud)

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

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

asg*_*oth 5

这取决于:

如果你立即放入$scope使用,例如在a 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;
     }
  };
});
Run Code Online (Sandbox Code Playgroud)

一点解释.数据随服务中的事件一起到达.那时getApp()可能已经被召唤过了.但这并不重要,因为这$q将确保数据仅在以后到达时进行过滤.控制器不需要知道,只要它不尝试做以下事情:

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

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

$scope.$watch('app', function(value) {
   ...
}, true);
Run Code Online (Sandbox Code Playgroud)

编辑:

在我看来,Search当你在自己的情况下使用它时,你的情况还没有解决$routeProvider:

Notes.index({subject_id: 1 }, Search)
Run Code Online (Sandbox Code Playgroud)

因此,请尝试解决SearchNotes在控制器中使用您的资源.

您需要在Search服务中返回承诺.两种选择:

  • 如果您需要先对数据执行某些操作,请返回$ http承诺,但这可能不是您想要的
  • 使用$ q并返回其承诺

$ q示例:

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;
});
Run Code Online (Sandbox Code Playgroud)