无法在我的控制器中访问我的服务(未定义) [英] Can't access my service in my controller (undefined)
问题描述
我正在尝试创建一个服务来执行一些 AJAX 请求.但是,当我尝试在我的控制器中用它做一些事情时,我的服务总是变得未定义.这是我的代码.
I am trying to create a service to do some AJAX requests. However, my service keeps getting undefined when I try to do something with it in my controllers. Here is my code.
我在这里找到了很多示例,并且我尝试遵循其中的很多示例,但是无论我做什么,我的服务都一直未定义.
I have found a lot of examples on here, and I've tried to follow a lot of them but no matter what I do my service keeps getting undefined.
我的服务:
MyApp.factory('myService', function($http) {
return {
findAll: function() {
return $http.get('/findAll')
.then(function(result) {
return result.data;
});
}
}
});
我的控制器:
MyApp.controller('UserController', ['$scope', '$http', 'myService', function($scope, $http, $log, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
}]);
我认为我没有正确注入它,但我看不出有什么问题.我对 Angular 还很陌生,所以..任何指针将不胜感激.
I assume I don't inject it correctly but I can't see whats wrong. I'm fairly new to Angular so.. Any pointers would be appreciated.
推荐答案
从注入中删除 $log
.您当前正在将 myService
服务命名"为 $log
,因此控制器内的 myService
是 undefined
.
Remove $log
from the injection. You are currently "naming" the myService
service to $log
and therefore myService
inside the controller is undefined
.
MyApp.controller('UserController', ['$scope', '$http', 'myService',
function($scope, $http, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
}]);
第二种解决方案
为了避免像这样命名"服务,可以不命名地注入它们.
2nd solution
To avoid having to "name" the services like this it's acceptable to inject them without naming them.
MyApp.controller('UserController', function($scope, $http, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
});
只要记得去掉右括号.
这篇关于无法在我的控制器中访问我的服务(未定义)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!