AngularJS控制器使用工厂功能

时间:2015-09-23 12:49:18

标签: javascript angularjs

我有以下代码,其中controller使用factory函数通过api请求获取用户数据。

控制器

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');
            }
        }
    });

现在在我console.log(response.data)的控制器中,json数据可用,但当我console.log($scope.getProfile())时,它是未定义的。

谢谢!

2 个答案:

答案 0 :(得分:1)

以下是答案,请阅读以下内容以了解这一概念。

  1. 您正在为范围变量 $ scope.user 分配值,因此您可以为其进行记录。
  2. 您的回复成功,所以您也可以再次登录。
  3. 但是当你尝试记录 console.log($ scope.getProfile())时,它不会返回任何内容。在角度中你可以保留在范围对象中的所有东西。

答案 1 :(得分:0)

如果你得到response.data,那么下面的代码应该可以正常工作。

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();
});
相关问题