I operate a factory that uses an api call to request user data:
angular.module('MyApp')
.factory('UserApi', function($auth,Account){
return {
getProfile: function()
{
Account.getProfile()
.then(function(response){
return response.data; ----> successful retrieval of json data!!
});
}
}
});
However, when I invoke the function in the controller, it returns undefined
myApp.controller('AppCtrl', function($rootScope,$state,$window,$document,$scope,$filter,$resource,cfpLoadingBar,$translate,UserApi){
$scope.user = function(){
UserApi.getProfile().then(function(data){
$scope.currentUser = data;
})
}
console.log($scope.user()); ----> undefined
});
account factory:
angular.module('MyApp')
.factory('Account', function($http){
return {
getProfile: function(){
return $http.get('/api/me');
}
}
});
The console error message is
TypeError: Cannot read property 'then' of undefined
EDIT
The only solution available is to assign the response.data
to $rootScope.user
so that the data can be accessed across all controllers.
angular.module('MyApp')
.factory('UserApi', function($auth,Account,$rootScope){
return {
getProfile: function()
{
Account.getProfile()
.then(function(response){
$rootScope.user = response.data; ----> successful retrieval of json data!!
});
return $rootScope.user;
}
}
});