Can't access my service in my controller (undefined)

久未见 提交于 2020-01-14 03:42:13

问题


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.

My service:

MyApp.factory('myService', function($http) {

return {
    findAll: function() {
        return $http.get('/findAll')
        .then(function(result) {
            return result.data;
        });
    }
   }
});

My Controller:

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


}]);

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.


回答1:


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

Just remember to remove the closing bracket aswell.



来源:https://stackoverflow.com/questions/27589490/cant-access-my-service-in-my-controller-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!