我试图通过扩展默认构建自定义Angular 2 http请求,我使用Ionic 2本地存储来存储身份验证令牌。 (将来可能会使用文件系统)。我的问题是如何从我的http服务返回已解决的承诺,以便我可以订阅我的组件中的Observable。我试过Observable.fromPromise和其他变化无济于事。从承诺内部返回解决Observable
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
// Get the token used for this request.
// * Need to return this promise resolved.
var promise = this.storage.get('token').then(token => {
if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
if (!options) {
// let's make option object
options = {headers: new Headers()};
}
options.headers.set('Authorization', 'Basic ' + token);
} else {
// we have to add the token to the url object
url.headers.set('Authorization', 'Basic ' + token);
}
return super.request(url, options).catch(this.catchAuthError(this));
}).catch(error => {
console.log(error);
});
}
想法基于此博客文章,但离子存储返回承诺。 http://www.adonespitogo.com/articles/angular-2-extending-http-provider/
谁是'user'? –
应该是令牌。 –
在'then'中处理observable是不方便的。我猜它应该像'return Observable.fromPromise(this.storage.get('token'))。map(token => {...; return url})。mergeMap(url => super.request(。 ..))' – estus