2016-11-30 76 views
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()结果。

+0

简短的回答,你不能。您的授权服务将不得不返回一个承诺。有一个提案将一项新功能[等待](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)添加到该语言中,但这是一种解决方法。 – teppic

回答

0

首先:在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 
});