【问题标题】:Angular-JS strict-DI doesn't like injecting resolved results from $routeProviderAngular-JS strict-DI 不喜欢从 $routeProvider 注入解析的结果
【发布时间】:2015-04-01 13:51:56
【问题描述】:

我在缩小 Angular 代码时遇到了一些问题,所以我打开了 ng-strict-di

一个问题似乎在于我在 app.js 配置中解决路由承诺的方式

.when('/:userId', {
           templateUrl: 'views/main.html', 
           controller: 'MyCtrl',  
           resolve : {
               myDependency : function(Cache, Model, $route){ 
                  return Cache.getCached( $route.current.params.userId); 
               } 
           }
      })

然后我将这个已解决的承诺注入 MyCtrl 控制器

angular.module('myApp') 
    .controller('MyCtrl',[ 'myDependency',  '$scope', '$rootScope', '$timeout', function (myDependency, $scope, $rootScope, $timeout) { 
 etc... 

但是我从 Angular 得到一个错误

[Error] Error: [$injector:strictdi] myDependency is not using explicit annotation and cannot be invoked in strict mode 

问题似乎可以追溯到 app.js 中的解析定义,因为我可以在解析中更改“myDependency”的名称,并且错误消息使用那里的名称而不是 myCtrl 中的依赖项名称。我在 myCtrl 控制器中明确列出了依赖项的名称。该应用程序可以运行,但由于此错误的问题,我无法缩小此代码。

【问题讨论】:

  • Mahesh 是对的(如下),但我发现我的解决方案是运行 ng-annotate 任务以删除并重新编写依赖项。 ng-strict-di 在突出问题区域方面非常有用。

标签: angularjs


【解决方案1】:

也按照 strict-di 进行解析。希望这有效!

resolve : {
           myDependency : ['Cache', 'Model', '$route', function(Cache, Model, $route){ 
               return Cache.getCached( $route.current.params.userId); 
           } 
     ]}

【讨论】:

  • 我想知道这样的事情是否可行,但是我收到一个错误,即我的“缓存”和“模型”依赖项(它们是我的自定义依赖项)不被称为提供程序。出于同样的原因,我无法将它们注入到配置的上一级。感谢您提出一些建议,因为我对此感到摸不着头脑。
  • 我在构建中添加了一个 gulp-ng-annotate 任务,现在事情已经修复(我使用 remove 和 add 来重写我的所有注释)。奇怪,因为 resolve 子句已按照您的建议进行了转换,现在它可以工作了。再次感谢您的建议。
【解决方案2】:

我遇到了同样的问题,@Mahesh Sapkal 的解决方案是正确的。

但是如果详细看这个,那么我的问题是ng-annotate 没有正确检测到必须注释的函数。所以我添加了 /@ngInject/ 评论,它现在可以工作了!

app.config(/*@ngInject*/function ($routeProvider) {
    $routeProvider
        .when('/tables', {
            template: templateList,
            controller: 'TableListController',
            resolve: {
                initial: /*@ngInject*/function (tableListControllerInitial) {
                    return tableListControllerInitial();
                }
            }
        })

【讨论】:

    猜你喜欢
    • 2018-01-16
    • 2015-05-13
    • 2016-12-31
    • 2019-07-03
    • 2012-01-14
    • 1970-01-01
    • 2015-09-05
    • 2020-11-23
    • 1970-01-01
    相关资源
    最近更新 更多