Title: How to return a Observable in promise function
Tags: observable;angular8;angular-promise
Question: I have written an http interceptor in ionic + capacitor + angular. Since I'm using capacitor I'm accessing storage in promise function. But http interceptor excepts us to return HttpEvent Observable. Here is my code
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Plugins } from '@capacitor/core';
const { Storage } = Plugins;
@Injectable()
export class Interceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any&gt;, next: HttpHandler): Observable<HttpEvent<any&gt;&gt; {
this.getItem().then(value =&gt; {
const token = value['value'];
if (token) {
request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) });
}
if (!request.headers.has('Content-Type')) {
request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
}
request = request.clone({ headers: request.headers.set('Accept', 'application/json') });
return next.handle(request).pipe(
map((event: HttpEvent<any&gt;) =&gt; {
if (event instanceof HttpResponse) {
}
return event;
}));
});
async getItem() {
return await Storage.get({ key: 'revolt-token' });
So far I have tried
return from(this.getItem()).pipe(map(data =&gt; {
return next.handle(request).pipe(
map((event: HttpEvent<any&gt;) =&gt; {
if (event instanceof HttpResponse) {
}
return event;
}));
});
But it returns Observable<Observable<HttpEvent<any&gt;&gt;&gt; but I want Observable<HttpEvent<any&gt;&gt;
Can someone help me identify how to return a Observable from a Promise. Thank you.

Here is the accepted answer: The answer is pipe switchMap instead of map
in return from(this.getItem()).pipe(map(data => {}));
Comment for this answer: Super excited to see you flesh this answer out.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:04/02/20', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<observable><angular8><angular-promise>', 'Title': 'How to return a Observable in promise function', 'ViewCount': 447, 'id': 60992020, 'user_AboutMe': '<p>Enthusiastic Front End Developer</p>\n', 'user_AccountId': 8604337.0, 'user_DisplayName': 'e.k', 'user_Reputation': 1255.0, 'user_Views': 167.0, 'user_id': 6444945.0}}