我有这段代码:
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Storage } from '@ionic/storage';
import { AppSettings } from './shared';
@Injectable()
export class HttpClient {
constructor(private http: Http, private storage: Storage) { }
createAuthorizationHeader(headers: Headers) {
var token: string = '';
this.storage.get(AppSettings.StorageKeys.Token).then(value => {
token = value;
});
headers.append('Authorization', 'Bearer ' + token);
}
get(url) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.get(url, {
headers: headers
});
}
post(url, data) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.post(url, data, {
headers: headers
});
}
}
这里的问题是:
this.storage.get(AppSettings.StorageKeys.Token).then(value => {
token = value;
});
这是承诺。那么如何更改createAuthorizationHeader
函数,以便正确附加标题?
这是Ionic2代码,但大多数问题与承诺的工作有关。
答案 0 :(得分:2)
返回标头承诺,然后从该承诺链接http调用。同样get
方法应该在Observable
之前返回承诺,因为您可以.toPromise()
使用http.get
方法。
createAuthorizationHeader() {
return this.storage.get(AppSettings.StorageKeys.Token).then(value => {
let headers = new Headers();
var token: string = '';
token = value;
headers.append('Authorization', 'Bearer ' + token);
return headers;
});
}
get(url) {
//let headers = new Headers();
return this.createAuthorizationHeader().then(headers => {
return this.http.get(url, { headers: headers }).toPromise();
});
}
对post
函数执行相同操作。
我会失去Observable并且必须与承诺合作。
如果您希望使用observables,请在链接两个承诺后转换承诺:
get(url) {
//let headers = new Headers();
var promise = this.createAuthorizationHeader().then(headers => {
return this.http.get(url, { headers: headers }).toPromise();
});
return Observable.fromPromise(promise);
}
答案 1 :(得分:2)
createAuthorizationHeader
不返回承诺,您应该从承诺功能成功创建Authorization
令牌。此外,get
您的服务应该返回承诺,同样,您可以使用.toPromise()
返回promise
,尽管Observable。但是,由于您没有赢得可观察到的酱油,您应该考虑将createAuthorizationHeader
方法转换为返回Observable
。 Observable.fromPromise
会在这种情况下拯救我们,将Promise
转换为Observable
。
<强>代码强>
createAuthorizationHeader(headers: Headers) {
var token: string = '';
let headers = new Headers();
return Observable.fromPromise(this.storage.get(AppSettings.StorageKeys.Token)
.then(value => {
token = value;
headers.append('Authorization', 'Bearer ' + token);
return headers;
}
);
}
get(url) {
return this.createAuthorizationHeader()
.switchMap((headers)=> this.http.get(url, {
headers: headers
});
})
}