angular 2 - 异步问题
angular 2 - asynchrone issue
我有一个非常简单的 Typescript 脚本(ionic2 和 angular2),它在 HTTP 调用之前添加了身份验证 header。这是想法(简化代码):
function CreateAuthorization(){
this.header.append('tests' : 'test')
Storage.retrieve('Auth').then(data){
this.header.append('authorization' : data.token)
}
}
function customHttp(url){
CreateAuthorization();
Http.get(url, this.header);
}
在我的请求 header 中,我有 'test' = 'test' 但我没有 'authorization' = 'MyToken'.
如何在 Storage.retrieve('Auth') 中设置 header 排序为 "wait"?
我知道我可以使用 setTimeout(),但我不喜欢这种肮脏的解决方法。
解决方案可能是 observable/promise 但我并没有真正掌握这些东西。
任何帮助将不胜感激:)
杰弗里
这是因为您的 CreateAuthorization
方法是异步的。当实际添加 Authorization
header 时,我会尝试利用承诺链来通知:
createAuthorization() {
this.header.append('tests' : 'test');
return Storage.retrieve('Auth').then(data){
this.header.append('authorization', data.token);
return true;
}
}
customHttp(url) {
this.createAuthorization().then(() => {
this.http.get(url, { headers: this.header });
});
}
我有一个非常简单的 Typescript 脚本(ionic2 和 angular2),它在 HTTP 调用之前添加了身份验证 header。这是想法(简化代码):
function CreateAuthorization(){
this.header.append('tests' : 'test')
Storage.retrieve('Auth').then(data){
this.header.append('authorization' : data.token)
}
}
function customHttp(url){
CreateAuthorization();
Http.get(url, this.header);
}
在我的请求 header 中,我有 'test' = 'test' 但我没有 'authorization' = 'MyToken'.
如何在 Storage.retrieve('Auth') 中设置 header 排序为 "wait"?
我知道我可以使用 setTimeout(),但我不喜欢这种肮脏的解决方法。
解决方案可能是 observable/promise 但我并没有真正掌握这些东西。
任何帮助将不胜感激:)
杰弗里
这是因为您的 CreateAuthorization
方法是异步的。当实际添加 Authorization
header 时,我会尝试利用承诺链来通知:
createAuthorization() {
this.header.append('tests' : 'test');
return Storage.retrieve('Auth').then(data){
this.header.append('authorization', data.token);
return true;
}
}
customHttp(url) {
this.createAuthorization().then(() => {
this.http.get(url, { headers: this.header });
});
}