Angular $injector——为Angular提供的未知提供商's $timeout

Angular $injector - Unknown Provider for Angular's $timeout

本文关键字:Angular timeout 提供商 injector 未知      更新时间:2023-09-26

我试图在一个应该在我的应用程序中的几个控制器中调用的方法中注入angular的$timeout服务。然而,我总是得到错误:

错误:[$injector:unpr]未知提供商:$timeoutProvider <->$timeout

当然$timeout必须是已知的,因为它是一个angular服务,所以我不明白为什么会发生这个错误。

这是我的代码:

HTML:
<div ng-app="app" ng-controller="sampleController">
    <button ng-click="doit()">Do It!</button>
</div>
JAVASCRIPT:
var app = angular.module('app', []);
app.controller('sampleController', ['$scope', function($scope) {
    var _this = this;
    $scope.doit = function() {
        var $injector = angular.injector();
        var $timeout = $injector.get('$timeout', _this);
        $timeout(function () { alert('ok'); });
    };
}]);

下面是演示这个问题的示例:

https://jsfiddle.net/fvw8zss5/


  • 这不是一个关于这是否是一个坏做法的问题。这当然不好。这是一个关于为什么不工作的问题。
  • 如果你知道如何使用JsFiddle, JsFiddle将工作。

angular.injector()只能在每个应用中使用一次,而不能在每个模块中使用。你应该通过DI使用$injector来获得实例化的注入器。话虽如此,将ng模块添加到列表中可以通过创建一个新的注入器来"解决"这个问题(不推荐)

看一下这个问题的完整解释和更合适的解决方案。

我想我明白你的意思了,你想要一个函数对所有25个控制器可用,而不必为所有25个控制器做依赖注入,你不想做一个服务,因为你必须把这个服务注入到所有25个控制器。

老实说,如果你想让这个函数在25个控制器上可用,你将不得不在所有25个控制器上做一个DI,无论是$timeout, service还是$rootScope方法

假设这25个控制器都没有父控制器,下面是$rootScope版本:

angular.module('fooApp').run(['$rootScope', '$timeout', function($rootScope, $timeout) { 
    $rootScope.doit = function() {
       //Insert function here with $timeout        
    };
}]);

你必须在所有的控制器中注入$rootScope来运行这个函数。

我认为你最好的选择是使用一个服务,或者至少下次设置你的应用程序,这样你就有了一个父控制器

为什么不直接把它注入到你的控制器声明中呢

app.controller('sampleController', ['$scope','$timeout', function($scope,$timeout)

为什么不使用指令而不是在每个控制器中重复工作?

<div ng-app="app" ng-controller="sampleController">
    <button do-it>Do It!</button>
</div>

脚本端:

app.directive('doIt', function ($timeout) {
    return {
        restrict: 'A',
        link: function ($scope, $element, $attr) {
            $element.on('click', function () {
                $timeout(function () { alert('ok'); });
            });
        }
    };
});