I am currently working on creating a customized Angular 2 http request by extending the default functionality, and I am using Ionic 2 local storage to save the authentication token. My main challenge lies in figuring out how to return a resolved promise from my http service so that I can subscribe to the Observable within my component. Despite trying variations like Observable.fromPromise, I have not been successful.
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
// Retrieve the token for this request.
// * Need to resolve this promise before returning it.
var promise = this.storage.get('token').then(token => {
if (typeof url === 'string') {
if (!options) {
// create option object
options = {headers: new Headers()};
}
options.headers.set('Authorization', 'Basic ' + token);
} else {
// 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);
});
}
This concept is based on a blog post, but Ionic storage returns a promise instead.