0

我遇到了 Angular 1 的下一个“问题”。

我有这个工厂,用于获取当前登录用户的数据:

angular.module('myModule')
  .factory('authFactory', function ($http, $rootScope, Session, api, backend_url) {
    var authFactory = this;
    var user = {};

    authFactory.init = function(){
        // This API returns the information of the current user
        api.current_user.get({}).$promise.then(function(res){
          user = res;
        });
    }

    // I use this function to return the user
    authFactory.user = function () {
         return user;
    };
  }

这是一个基本的控制器示例,我试图访问上述工厂检索到的信息:

angular.module('myModule.mypage')
.controller('PageCtrl', function ($scope, authFactory) {     
  $scope.user = authFactory.user();
  authFactory.init();

  angular.element(document).ready(function () {
      // This will return {} because it's called
      // before the factory updates user value
      console.log(authFactory.user());
      console.log($scope.user);
  });
});

问题是$scope.user = myFactory.user(); 一旦工厂检索到用户值,就不会更新。

我认为我的问题与myFactory.user(); . 我正在使用一个函数,所以函数返回的值在myFactory.user更改后没有更新,我认为这就是为什么在PageCtrl上变量$scope.user没有得到任何值。

我的问题是:

  • 在我的控制器上等待用户信息由authFactory加载的最佳方法是什么?

  • 我应该改用服务吗?

4

2 回答 2

1

您的实现的问题是在使用大概异步 API 调用user时正在初始化。authFactory.init()

我建议你从authFactory.user方法中返回承诺。

angular.module('myModule')
.factory('authFactory', function ($http, $rootScope, Session, api, $q, backend_url) {
    var authFactory = this;
    var user = {};

    authFactory.init = function () {
        // This API returns the information of the current user
        return api.current_user.get({}).$promise.then(function (res) {
            user = res;
        });
    }

    //Return promise from the method
    authFactory.user = function () {
        var deferred = $q.defer();
        if (angular.isDefined(user)) {
            deferred.resolve(user);
        } else {
            authFactory.init().then(function () {
                deferred.resolve(user);
            });
        }
        return deferred.promise;
    };
});

然后修改控制器

angular.module('myModule.mypage')
.controller('PageCtrl', function ($scope, authFactory) {
    authFactory.user().then(function (user) {
        $scope.user = user;
    })
});
于 2017-11-01T10:33:18.113 回答
0
angular.module('myModule')
  .factory('authFactory', function ($http, $rootScope, Session, api, backend_url) {
    var authFactory = this;

    authFactory.user = {}

    // I use this function to return the user
    authFactory.getUser() = function () {
          return api.current_user.get({}).$promise.then(function(res){
               authFactory.user = res;
          });
    };
  }


angular.module('myModule.mypage')
.controller('PageCtrl', function ($scope, authFactory) {     
  authFactory.getUser().then(function() {
       $scope.user = authFactory.user;
  });
});

给我们提供一个 JSFiddle,我试图在没有任何测试环境的情况下帮助你。

于 2017-11-01T10:33:12.853 回答