【问题标题】:ngResource return success callback result by servicengResource 通过服务返回成功回调结果
【发布时间】: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


【解决方案1】:

首先:在你的authorizationService 中注入$q

试试这个:

authorization: function(user) {
  return $q(function(resolve, reject) {
    tokenService.post({}, {
      grant_type: 'password',
      username: user.login,
      password: user.password,
      client_id: user.clientId
    })
    .$promise
    .then(function(token) {
      resolve(token);
    })
    .catch(function(err) {
      reject(err);
    });
  });
}

然后,在您的控制器中,您可以使用:

authorizationService.authorization(user)
.then(function(token) {
  // Some code here
})
.catch(function(err) {
  // Handle error here
});

【讨论】:

    猜你喜欢
    • 2010-09-05
    • 1970-01-01
    • 2013-03-31
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    相关资源
    最近更新 更多