返回工厂已解决承诺的结果

Returning result of a resolved promise from factory

我有一个 Angular 应用程序,其中包含一个在 av MVC 视图中定义的菜单。所以菜单与应用程序中的路线无关。在菜单控制器中,我想注入一个包含当前用户数据的对象。然后我将循环这个对象来决定哪些菜单项应该对用户可见。

工厂长这样:

.factory('currentUser', ['currentUserResource', function (currentUserResource) {return currentUserResource.get()}]) 

get 方法是标准的 $resource GET 方法。

问题是,工厂 returns 需要很短时间才能解决的承诺。所以在我的控制器中,一些菜单项在 promise 被解决之前被处理,并且没有显示它们应该显示的时间。

在我的控制器中注入 'currentUser',然后尝试以这些方式使用:

$scope.currentUser = currentUser.then(function (data){
  return data
});

$scope.currentUser = currentUser;

currentUser.then(function(data){
  $scope.currentUser = data;
});

有什么方法可以在不使用路由解析的情况下确保在加载控制器之前解析 currentUser,或者至少在控制器执行的第一件事中解析它?

使用$resource对象的$promise属性来延迟控制器的工作。

resourceObject.$promise.then ( function onFulfilled(object) {
    //Do work that needs fulFilled object
}).catch (function onRejected(response) {
    console.log(response.status)
});;

如果resourceObject已经解决,onFulfilled函数将立即执行。如果 resourceObject 还没有被解析,$q 服务将在调用 onFulfilled 函数之前等待。

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

The Resource instances and collections have these additional properties:

  • $promise: the promise of the original server interaction that created this instance or collection.

    On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.

    On failure, the promise is rejected with the http response object, without the resource property.

-- AngularJS $resource Service API Reference