gpt4 book ai didi

javascript - 使用工厂函数的 AngularJS Controller

转载 作者:行者123 更新时间:2023-12-03 08:49:44 24 4
gpt4 key购买 nike

我有以下代码,其中 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())它是未定义的。

谢谢!!

最佳答案

这是答案,请阅读以下要点以理解这个概念。

  1. 您正在为作用域变量 $scope.user 赋值,因此您可以为其进行日志记录。
  2. 您已成功收到回复,因此您也可以再次登录此处。

但是当您尝试记录 console.log($scope.getProfile()) 时,它不会返回任何内容。在 Angular 中,您可以将所有内容保留在范围对象中。

关于javascript - 使用工厂函数的 AngularJS Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32740084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com