Jim*_*ton 4 dependency-injection angularjs
我在自己的模块中定义了一个服务:
angular.module('foteDatasetsService', [])
.factory('foteAPIservice', function($http) {
var foteAPI = {};
foteAPI.getDatasets = function() {
return $http({
method: 'JSONP',
url: 'http://localhost:8080/datasets?callback=JSON_CALLBACK'
});
}
return foteAPI;
});
Run Code Online (Sandbox Code Playgroud)
在另一个模块中,(在另一个文件中)我有一个控制器,我想用它:
angular.module('foteRequests').controller('foteRequestsController',
['$scope', function foteRequestsController($scope, foteAPIservice) {
//snip other stuff
$scope.datasets = [];
foteAPIservice.getDatasets().success(function (response) {
//Digging into the response to get the relevant data
$scope.datasets = response;
console.log(response);
});
]);
Run Code Online (Sandbox Code Playgroud)
我在一个名为init .js 的文件中有一个init模块,它包含如下依赖项:
'use strict';
angular.module('foteRequests', ['foteDatasetsService']);
Run Code Online (Sandbox Code Playgroud)
它看起来并不像实际上将foteDatasetsService注入控制器.如果我运行该应用程序,我收到一个错误:
Cannot call method 'getDatasets' of undefined
Run Code Online (Sandbox Code Playgroud)
因此,如果我通过在控制器中包含foteDatasetsService来强制解决问题,如下所示:
angular.module('foteRequests').controller('foteRequestsController', ['$scope',
'foteDatasetsService', function foteRequestsController($scope, foteAPIservice) {
...
}]);
Run Code Online (Sandbox Code Playgroud)
它给了我这个错误:
Error: [$injector:unpr] Unknown provider: foteDatasetsServiceProvider <- foteDatasetsService
Run Code Online (Sandbox Code Playgroud)
编辑:我希望能够将此服务注入3个需要获取相同信息的控制器.
任何想法为什么工厂没有创建提供商?我迷失在那一个......
而不是这个:
angular.module('foteRequests').controller('foteRequestsController',
['$scope', 'foteDatasetsService', function foteRequestsController($scope, foteAPIservice)
{ ... }]);
Run Code Online (Sandbox Code Playgroud)
试试这个:
angular.module('foteRequests').controller('foteRequestsController',
['$scope', 'foteAPIservice', function foteRequestsController($scope, foteAPIservice)
{ ... }]);
Run Code Online (Sandbox Code Playgroud)
你已经拥有injected了foteDatasetsService,现在你只想要inject这项服务foteAPIservice.
UPDATE作为@dtabuenc说这将是最好不要追加Service一个module名称.
| 归档时间: |
|
| 查看次数: |
12449 次 |
| 最近记录: |