Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度2同步承诺_Javascript_Angular_Angular Promise_Ionic2 - Fatal编程技术网

Javascript 角度2同步承诺

Javascript 角度2同步承诺,javascript,angular,angular-promise,ionic2,Javascript,Angular,Angular Promise,Ionic2,在Ionic 2中,用于访问localStorage的get函数返回一个承诺。下面代码的问题是头对象在附加授权键之前返回。我如何修改下面的函数,使headers对象仅在解析承诺后返回 private _createAuthHeaders(): Headers { let headers = new Headers({ 'Accept': 'application/json', 'Content-Type': 'application/json' }

Ionic 2
中,用于访问
localStorage
get
函数返回一个承诺。下面代码的问题是
对象在附加
授权
键之前返回。我如何修改下面的函数,使
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...
});
编辑

您可以利用承诺链接使代码更干净。以下是一个示例:

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

此外,函数的返回类型应该是
,但我只想让函数返回
标题
对象。由于我在调用者函数中创建了一个自定义的
request
对象,如果我必须处理其中的另一个承诺,代码就会变得更加混乱。简短的回答是:你不能;-)更长的答案是,你可以利用承诺链。。。我用这种方法的一个示例更新了我的答案。目前,我通过使用本机
window.localStorage.getItem('authToken')
函数解决了这个问题,该函数只返回
字符串
类型。但我应该坚持使用框架,并在某个时候对其进行重构。非常感谢。