“错误:未知提供程序”试图在Angular.JS中实现依赖项注入

时间:2013-09-10 19:18:18

标签: angularjs

我是Angular.JS的新手,我正在尝试进行依赖注入,但我得到了这个:

// Definition
app.factory('Reload', function (load, $timeout, timeout) {
    if (!timeout) {
        timeout = 15 * 1000; // reload page every quater minute by default
    }
    return $timeout(load, timeout);
});


// Controller
app.controller('SomeController', function ($scope, $routeParams, $location, $timeout, Installer, Reload) {
  Reload(load, $timeout, 1000);
});

Error: Unknown provider: loadProvider <- load <- Reload
    at Error (<anonymous>)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2734:15
    at Object.getService [as get] (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2862:39)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2739:45
    at getService (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2862:39)
    at Object.invoke (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2880:13)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2740:37
    at getService (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2862:39)
    at invoke (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2880:13)
    at Object.instantiate (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2914:23)

我错过了什么?感谢

3 个答案:

答案 0 :(得分:2)

Reload工厂的定义在工厂定义和它返回的函数之间混淆。更新您的代码如下。

// Definition
app.factory('Reload', function ($timeout) {
    return function(load, timeout) {
        if (!timeout) {
            timeout = 15 * 1000; // reload page every quater minute by default
        }
        return $timeout(load, timeout);
    }
});


// Controller
app.controller('SomeController', function ($scope, $routeParams, $location, $timeout, Installer, Reload) {
  Reload(load, 1000);
});

答案 1 :(得分:1)

您将load提供者传递到Reload,这意味着需要在应用中声明服务load

如果我理解正确,我认为你需要添加

app.factory('load', function(){
  document.reload();
});

在你的Reload声明之前,如果你在同一个文件中做了所有这些。

话虽如此,除非您需要特别复杂的重新加载,否则我只需从注射中取出load并将其包含在$timeout

return $timeout(document.reload, timeout);

答案 2 :(得分:1)

我解决了将代码更改为:

// Factory definition
app.factory('Reload', function ($timeout) {
    return function (fnLoad, timeout) {
        if (!timeout) {
            timeout = 15 * 1000; // reload page every quater minute by default
        }
        return $timeout(fnLoad, timeout);
    };
});

// Controller
app.controller('InstallersController', function ($scope, $routeParams, $location, $timeout, Installer, Reload) {
  Reload(load);
}

感谢同事......