无法访问我的服务我的控制器(不确定) [英] Can't access my service in my controller (undefined)
问题描述
我想创建一个服务做一些AJAX请求。
然而,当我试着用它做的东西在我的控制器我的服务不断得到不确定的。这里是我的code。
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();
}]);
我以为我没有正确地注入,但我看不出什么错。我是相当新的角等等..
任何指针将AP preciated。
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.
推荐答案
删除 $日志
。您正在命名的为myService
服务 $日志
,因此为myService
控制器内部的未定义
。
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();
}]);
结果
第2解决方案结果
为了避免在名称像这样这是可以接受注入他们的服务不点名。
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();
});
不过,别忘了取出右括号以及。
Just remember to remove the closing bracket aswell.
这篇关于无法访问我的服务我的控制器(不确定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!