【问题标题】:AngularJS controller using factory functionAngularJS 控制器使用工厂函数
【发布时间】:2015-09-23 21:19:51
【问题描述】:

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

谢谢!!

【问题讨论】:

  • 因为你的函数没有返回任何值。您应该在成功回调时返回值/对象。
  • @Vineet return $scope.user 不起作用..
  • 调用 Account.getProfile() 是异步的,您对 $scope.getProfile() 的调用不会等到执行回调。即使你在 callbak 中返回了一些东西,也没有人能抓住它。
  • 这看起来是异步函数的正常预期行为。异步函数的全部意义在于允许您的代码在等待某事(在本例中为来自服务器的响应)时继续执行其他工作。 .then 块中的任何事情都将在 未来 发生,任何外部的事情发生在 现在,你不能现在记录你期望在未来发生的事情。
  • 在 Angular 的情况下,因为 Angular 在 $scope 上创建了一个事件观察器,当未来事件完成时($scope.user 填充了一个值),那么 Angular 将运行 $digest 和更新 DOM。

标签: javascript angularjs


【解决方案1】:

这里是答案,阅读下面的点来理解这个概念。

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

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

【讨论】:

  • 这很有意义..谢谢
【解决方案2】:

如果你得到 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();
});

【讨论】:

  • 它返回一个空对象{}。
  • @novavent,尝试记录 response.data,如果你得到有效值,那么你肯定也应该得到 $scope.user 的数据。
  • 在函数内部,我可以获取 json 数据,但只有在记录 getProfile() 外部时,除了 undefined/Object {},我什么也得不到。无论如何,我的视图仍然可以使用 $scope 中的数据。
  • 你不会得到。正如@Thangadurai 所建议的那样。 getProfile 方法是异步的。只有在获得成功或失败响应后才能使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多