4

我已经配置了resolve几个路由的参数来返回一个承诺,以便延迟控制器的实例化,直到承诺得到解决。目前我正在使用函数表示法,而不是指定要注入的字符串。

例如:

.when('/article/:id', {
    templateUrl: 'app/article/article.html',
    controller: 'ArticleController',
    resolve: {
        article: ['Content', '$route', function (Content, $route) {
            return Content.get({ contentId: $route.current.params.id }).$promise;
        }]
    }
})

article参数正确地注入了已解决的承诺值。

但是,我想保持它干燥并通过指定一个字符串来注入这个值,如文档中所述

当我设置一个工厂函数来提供这样的承诺时,实例只被正确注入一次(第一次)。此后,由于 AngularJS 注入服务已经缓存了该实例,因此使用了相同的 promise。

.factory('contentPromise', ['Content', '$route', function (Content, $route) {
    return Content.get({ contentId: $route.current.params.id }).$promise;
}])

是否可以指定每次请求时都必须运行工厂函数?或者以其他方式实现我的目标?

4

1 回答 1

7

您拥有的第一个示例是要走的路,我认为您可以像这样走一点“DRYer”:

.when('/article/:id', {
    ...
    resolve: {
        article: ['contentPromise', function (contentPromise) {
            return contentPromise();
        }]
    }
})

服务:

.factory('contentPromise', ['Content', '$route', function (Content, $route) {
    return function() {
        return Content.get({ contentId: $route.current.params.id }).$promise;
    };
}])
于 2014-02-12T17:56:55.623 回答