【发布时间】:2017-04-15 06:24:00
【问题描述】:
我最近开始了使用 AngularJs 的冒险,但对 promises 和返回异步数据的想法让我不知所措。
我正在尝试通过 .factory 方法和 $resource 服务来完成简单的数据返回。
这是我的 $resource 服务返回承诺
(function () {
angular.module('token')
.factory('tokenService', ['$resource', 'baseUri', tokenService]);
function tokenService($resource, baseUri) {
return $resource(baseUri + 'token', {}, {
post: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
});
}
})();
我在另一个应该返回数据的服务中使用此服务。
(function () {
angular.module('authorization')
.factory('authorizationService', ['$httpParamSerializer', 'tokenService', authorizationService]);
function authorizationService($httpParamSerializer, tokenService) {
return {
authorization: function(user){
var token = {};
tokenService.post({}, $httpParamSerializer({
grant_type: 'password',
username: user.login,
password: user.password,
client_id: user.clientId
}), function(response){
token = response;
console.log('authorizationResponse', response);
console.log('authorizationToken', token);
});
// .$promise.then(function(response){
// token = response;
// console.log('authorizationResponse', response);
// console.log('authorizationToken', token);
// });
console.log('finalToken', token);
return token;
}
};
}
})();
但我不能强制令牌变量在返回之前拥有 tokenService.post() 结果。
【问题讨论】:
-
简答,你不能。你的 authorizationService 必须返回一个 Promise。有一个提案草案要向该语言添加新功能 await,但还有一段路要走。
标签: angularjs service promise ngresource