2016-11-30 73 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 
});