简体   繁体   English

Angular2同步承诺

[英]Angular2 synchronous promise

In Ionic 2 the get function for accessing localStorage returns a promise. Ionic 2 ,用于访问localStorageget函数返回一个promise。 The problem with the below code is that the headers object gets returned before it has been appended with the Authorization key. 以下代码的问题在于,在将headers对象附加了Authorization密钥之前,将返回headers对象。 How could I modify the below function such that the headers object is returned only after the promise is resolved. 我如何修改以下函数,以便仅在答应解决后才返回headers对象。

private _createAuthHeaders(): Headers {
    let headers = new Headers({
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    });
    this.local.get('authToken').then(res=>{
      headers.append('Authorization', res);
    }, err=>{
      headers.append('Authorization', '');
    });
    return headers;
}

I would refactor your code this way: 我将以这种方式重构您的代码:

private _createAuthHeaders(): Headers {
  let headers = new Headers({
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  });
  this.local.get('authToken').then(res=>{
    headers.append('Authorization', res);
    return headers;
  }, err=>{
    headers.append('Authorization', '');
    return headers;
  });
}

and you can use this method like this: 您可以像这样使用此方法:

this._createAuthHeaders().then(headers => {
  // do something like setting the headers on the request
  // and execute it...
});

Edit 编辑

You can leverage promise chaining to make your code cleaner. 您可以利用Promise链来使代码更整洁。 Here is a sample: 这是一个示例:

this._createAuthHeaders().then(headers => {
  // do something like setting the headers on the request
  // and execute it...
  return this.http.get('some url', { headers: headers }).toPromise();
}).then(result => {
  // handle result
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM