【问题标题】:Using the ngRoute 'resolve' parameter with an injected promise使用带有注入承诺的 ngRoute 'resolve' 参数
【发布时间】:2014-03-11 05:00:35
【问题描述】:

我已经配置了几个路由的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 参数已正确注入解析的承诺值。

但是,我想保持它 DRY 并通过指定一个字符串来注入这个值,就像 mentioned in the documentation 一样。

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

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

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

【问题讨论】:

  • 第一个例子就是要走的路。
  • 嗨,我正在尝试做同样的事情。您在哪里/如何定义内容?我知道你正在使用 ngResource。内容是否在 .config 中定义?
  • 注册为工厂,返回$resource('api/Content/:id')

标签: javascript angularjs ngroute


【解决方案1】:

你的第一个例子是要走的路,我认为你可以像这样走一点“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;
    };
}])

【讨论】:

  • 调用服务resolve: {article:'getSomething'}和在resolve对象中定义它有什么区别?为什么每次访问视图时第一次只运行一次而第二次运行?
  • @ilyo,我相信这是因为 Angular 的服务和工厂是单例的,所以代码只会运行一次。 docs.angularjs.org/guide/services
猜你喜欢
  • 2017-07-10
  • 2018-01-06
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
相关资源
最近更新 更多