javascript – 将ngRoute’resolution’参数与注入的promise一起使用
作者:互联网
我已经配置了几个路由的resolve参数来返回一个promise,以便延迟控制器的实例化,直到解析了promise.目前我正在使用函数表示法,而不是指定要注入的字符串.
例如:
.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;
}]
}
})
使用已解析的promise值正确注入article参数.
但是,我想保持DRY并通过指定字符串来注入此值,如mentioned in the documentation所示.
当我设置工厂函数来提供这样的承诺时,实例只能正确注入一次(第一次).此后,使用相同的promise,因为AngularJS注入服务已缓存该实例.
.factory('contentPromise', ['Content', '$route', function (Content, $route) {
return Content.get({ contentId: $route.current.params.id }).$promise;
}])
是否可以指定每次请求时都必须运行工厂功能?或者以其他方式实现我的目标?
解决方法:
你拥有的第一个例子是要走的路,我想你可以这样做一点“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;
};
}])
标签:javascript,angularjs,ngroute 来源: https://codeday.me/bug/20190612/1226319.html