Using the ngRoute 'resolve' parameter with an injected promise

家住魔仙堡 提交于 2019-12-21 02:36:44

问题


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.

For example:

.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.

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?


回答1:


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

Service:

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


来源:https://stackoverflow.com/questions/21735221/using-the-ngroute-resolve-parameter-with-an-injected-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!