我在 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;
};
}
这是一个基本的 Controller 示例,我尝试访问上述工厂检索到的信息:
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);
});
});
问题在于,一旦 Factory 检索到用户值,$scope.user = myFactory.user(); 就不会更新。
我认为我的问题与myFactory.user();有关。我正在使用一个函数,因此在 myFactory.user 更改后,该函数返回的值不会更新,我认为这就是为什么在 PageCtrl 上变量 $ scope.user 没有获得任何值(value)。
我的问题是:
在我的 Controller 上等待 authFactory 加载用户信息的最佳方法是什么?
我应该使用服务吗?
最佳答案
您的实现存在的问题是,当使用异步 API 调用 authFactory.init()
时,user
正在初始化。
我建议您从 authFactory.user
方法返回 promise 。
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;
};
});
然后修改 Controller
angular.module('myModule.mypage')
.controller('PageCtrl', function ($scope, authFactory) {
authFactory.user().then(function (user) {
$scope.user = user;
})
});
关于javascript - Angular 1.6 : Factory issue initializing values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47052696/