MegaRacer MegaRacer - 3 months ago 10
AngularJS Question

Service function undefined

I am tryin the following code

In my services.js one of the services is

.service('AppService', ['$http', 'AuthService', function ($http, AuthService) {

var getUserData = function(){
return {
"fname": "Admin",
"lname": "ladmin",
"array" : [{}, {}]
}
}
return {
getUserData: getUserData
}
}]);


In my controller, I have

AppService.getUserData().then(function(response){
console.log(response);
}, function(err){
console.log(err);
})


Error :
AppService.getUserData(...).then is not a function


I have the service injected. What am I doing wrong ?

Answer

You are concatenating the then function in your call AppService.getUserData().then(function(response){, which implies your service should return a promise (but that's not your case).

To make your code work, remove the then function:

var data = AppService.getUserData(); //no promise used, your actual situation.

if you want to use a promise, leave your controller function as it is and modify your service like so:

.service('AppService', ['$http', 'AuthService', '$q', function ($http, AuthService, $q) {

    getUserData : function(){
       return $q(function(resolve, reject) {
          resolve({
               "fname": "Admin",
               "lname": "ladmin",
               "array" : [{}, {}]
           });
       }
    }       
}]);

this way, you'll use a promise (but in your example you don't need it, it's a simple call with a return)