I have a following code where controller
use factory
function to get user data via an api request.
controller
myApp.controller('UserApiCtrl', function($scope,$auth,Account){
$scope.getProfile = function(){
Account.getProfile()
.then(function(response){
$scope.user = response.data;
})
.catch(function(response){
// errors handled here
})
};
$scope.getProfile();
})
factory
angular.module('MyApp')
.factory('Account', function($http){
return {
getProfile: function(){
return $http.get('/api/me');
}
}
});
Now in controller when I console.log(response.data)
, json data is available, but when I console.log($scope.getProfile())
it's undefined.
Thanks!!
Here is the answer, read the below point to understand the concept.
But when you try to log console.log($scope.getProfile()) , it is not going to return anything. In angular every thing you can keep in scope object.
If you get response.data then below code should work fine.
myApp.controller('UserApiCtrl', function($scope,$auth,Account){
$scope.user = {}; // Change to [] if response.data is array
$scope.getProfile = function(){
Account.getProfile()
.then(function(response){
$scope.user = response.data;
console.log($scope.user);
})
.catch(function(response){
// errors handled here
})
};
$scope.getProfile();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.