如何使用$ q从AngularJS服务返回已解决的承诺? [英] How to return a resolved promise from an AngularJS Service using $q?
本文介绍了如何使用$ q从AngularJS服务返回已解决的承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的服务是:
myApp.service('userService', [
'$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {
var deferred;
deferred = $q.defer();
this.initialized = deferred.promise;
this.user = {
access: false
};
this.isAuthenticated = function() {
this.user = {
first_name: 'First',
last_name: 'Last',
email: 'email@address.com',
access: 'institution'
};
return deferred.resolve();
};
}
]);
我在 config
中调用它文件来自:
I'm calling this in my config
file via:
myApp.run([
'$rootScope', 'userService', function($rootScope, userService) {
return userService.isAuthenticated().then(function(response) {
if (response.data.user) {
return $rootScope.$broadcast('login', response.data);
} else {
return userService.logout();
}
});
}
]);
然而,它抱怨然后
不是一个功能。我不回复已解决的承诺吗?
However, it complains that then
is not a function. Aren't I returning the resolved promise?
推荐答案
从您的服务方式:
function serviceMethod() {
return $timeout(function() {
return {
property: 'value'
};
}, 1000);
}
在您的控制器中:
serviceName
.serviceMethod()
.then(function(data){
//handle the success condition here
var x = data.property
});
这篇关于如何使用$ q从AngularJS服务返回已解决的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文