簡體   English   中英

Angular2同步承諾

[英]Angular2 synchronous promise

Ionic 2 ,用於訪問localStorageget函數返回一個promise。 以下代碼的問題在於,在將headers對象附加了Authorization密鑰之前,將返回headers對象。 我如何修改以下函數,以便僅在答應解決后才返回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;
}

我將以這種方式重構您的代碼:

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;
  });
}

您可以像這樣使用此方法:

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

編輯

您可以利用Promise鏈來使代碼更整潔。 這是一個示例:

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