使用ngRoute'决心'参数与注入的承诺 [英] Using the ngRoute 'resolve' parameter with an injected promise

查看:201
本文介绍了使用ngRoute'决心'参数与注入的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经配置几条航线的解析参数,以延缓控制器的实例返回一个承诺,直到承诺得到解决。目前我使用的函数符号,而不是指定一个字符串来注入。

I have configured the resolve parameter of several routes to return a promise in order to delay instantiation of the controller until the promise is resolved. Currently I am using the function notation, rather than specifying a string to inject.

例如:

.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;
        }]
    }
})

文章参数正确的解决承诺值注入。

The article parameter is correctly injected with the resolved promise value.

不过,我想通过指定一个字符串,使其保持干燥并注入该值,是的在文档提及。

However, I would like to keep it DRY and inject this value by specifying a string, as is mentioned in the documentation.

当我成立了一个工厂函数提供像这样的承诺,该实例只正确注射一次(第一次)。此后,使用同样的承诺,因为AngularJS注射服务已缓存实例

When I set up a factory function to provide the promise like so, the instance is only injected correctly once (the first time). Thereafter, the same promise is used because the AngularJS injection service has cached the instance.

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

是否可以指定该工厂函数必须运行每次请求的时间?或达到我的目的以其他方式?

Is it possible to specify that the factory function must be run every time it is requested? Or to achieve my goal in some other way?

推荐答案

您的第一个例子是去了,我觉得你可以去一点点机像这样的方式:

The first example you have is the way to go, I think you could go a little bit "DRYer" like this:

.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;
    };
}])

这篇关于使用ngRoute'决心'参数与注入的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆