Angular2:等待http请求来定义变量

时间:2017-07-13 09:29:03

标签: angular http cookies token

我需要在我的getResource方法中请求资源服务器刷新我的令牌(包含在cookie中)。

之后,我将对cookie变量进行定值以构建到资源服务器的正确标头

  getResource(resourceUrl) {


var cookie;
var resultString;

if (!Cookie.get("access_token")) { //refresh workflow
  let params = new URLSearchParams();
  params.append('grant_type','refresh_token');
  params.append('refresh_token',Cookie.get("refresh_token"));
  params.append('client_id','web_app');

  let headers = new Headers({'Content-type': 'application/x-www-form-urlencoded; charset=utf-8','Authorization': 'Basic '+btoa("web_app:")});
  let options = new RequestOptions({headers: headers});

  this._http.post('http://localhost:9997/oauth/token',params.toString(),options)
    .map(res => res.json())
    .toPromise()
    .then(data =>{
      Cookie.set("access_token", data.access_token, 0.00034722222);
      Cookie.set("refresh_token", data.refresh_token, 1);
    });
}
  cookie = Cookie.get("access_token");//this must be valorize after expire with refresh

var headers = new Headers({
  'Content-type': 'application/x-www-form-urlencoded; charset=utf-8',
  'Authorization': 'Bearer ' + cookie});                          

var options = new RequestOptions({headers: headers});

return this._http.get(resourceUrl, options)
  .map(res => res.text())
  .toPromise();}

我正在尝试使用async / await模式,但我没有达到目标。有什么想法吗?

0 个答案:

没有答案