我有以下代码,其中 Controller
使用factory
函数通过API请求获取用户数据。
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();
})
工厂
angular.module('MyApp')
.factory('Account', function($http){
return {
getProfile: function(){
return $http.get('/api/me');
}
}
});
现在在 Controller 中,当我 console.log(response.data)
时,json 数据可用,但是当我 console.log($scope.getProfile())
它是未定义的。
谢谢!!
最佳答案
这是答案,请阅读以下要点以理解这个概念。
- 您正在为作用域变量 $scope.user 赋值,因此您可以为其进行日志记录。
- 您已成功收到回复,因此您也可以再次登录此处。
但是当您尝试记录 console.log($scope.getProfile()) 时,它不会返回任何内容。在 Angular 中,您可以将所有内容保留在范围对象中。
关于javascript - 使用工厂函数的 AngularJS Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32740084/