Currently, I'm working on an HttpInterceptor within my Ionic 4 application. My goal is to retrieve the Bearer Authorization token stored in local storage.
Although I attempted to utilize mergeMap for this task, I kept encountering the following error:
Property 'mergeMap' does not exist on type 'Observable<any>'
Below is the complete code snippet extracted from the file token.interceptor.ts:
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError, from } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { Storage } from '@ionic/storage';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
token: any;
constructor(private router: Router, private storage: Storage) {}
intercept(request: HttpRequest < any >, next: HttpHandler): Observable < HttpEvent < any >> {
return from(this.storage.get('User')).mergeMap((val) => {
if (this.token) {
request = request.clone({
setHeaders: {
'Authorization': this.token
}
});
}
if (!request.headers.has('Content-Type')) {
request = request.clone({
setHeaders: {
'content-type': 'application/json'
}
});
}
request = request.clone({
headers: request.headers.set('Accept', 'application/json')
});
return next.handle(request).pipe(
map((event: HttpEvent < any >) => {
if (event instanceof HttpResponse) {
console.log('event--->>>', event);
}
return event;
}),
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
if (error.error.success === false) {
// this.presentToast('Login failed');
} else {
this.router.navigate(['/']);
}
}
return throwError(error);
}));
})
}
}
In an attempt to resolve the issue mentioned in this thread, I experimented with the suggested format:
return from(...).pipe(mergeMap(...));
Unfortunately, this approach did not yield the desired outcome.
Could anyone provide alternative suggestions or solutions that I could explore?