"Error: Unknown provider"尝试在 Angular 中实现依赖注入.JS



我是 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)

我错过了什么?谢谢

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);
});

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

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

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

Reload声明之前,如果您在同一个文件中执行所有这些操作。

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

return $timeout(document.reload, timeout);

我解决了将代码更改为:

// 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);
}

感谢一位同事...

最新更新