0
我已经开始接受AngularJs的冒险,但承诺和返回异步数据的想法overhelmed我。ngResource通过服务返回成功回调结果
我试图通过.factory方法和$资源服务完成简单的数据返回。
这里是我的$资源服务返回的承诺
(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;
}
};
}
})();
但我不能强制令牌变量在returing之前拥有tokenService.post()结果。
简短的回答,你不能。您的授权服务将不得不返回一个承诺。有一个提案将一项新功能[等待](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)添加到该语言中,但这是一种解决方法。 – teppic