我正在尝试通过扩展默认值来构建自定义 Angular 2 http 请求,并且我正在使用 Ionic 2 本地存储来存储身份验证 token 。 (将来可能会使用文件系统)。我的问题是如何从我的 http 服务返回已解决的 promise ,以便我可以在我的组件中订阅 Observable。我试过 Observable.fromPromise 和其他变体都无济于事。
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);
});
}
想法基于这篇博文,但 Ionic 存储返回一个 promise 。 http://www.adonespitogo.com/articles/angular-2-extending-http-provider/
最佳答案
我不知道该存储是否返回与 Rx 兼容的 promise ,但如果是,那么解决方案应该如下所示:
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
return Observable
.fromPromise(this.storage.get('token'))
.flatMap(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));
});
});
}
如果 promise 与 observables 不兼容,仍然有办法做到这一点,尽管它不是那么优雅:
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
return Observable.create((observer: Observer) => {
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);
}
super.request(url, options).catch(this.catchAuthError(this)).subscribe(result => {
observer.next(result);
observer.complete();
});
}).catch(error => {
observer.error(error);
});
});
}
关于angular - 从 Promise 内部返回已解决的 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40899313/