In my Angular 6 app, I have a class that attaches API tokens to every http request using the getIdToken()
method. If the token retrieval is successful, everything works fine. However, if it fails, my app will stop functioning.
I need help with handling the mergeMap
function when getToken
fails. Any suggestions?
I'm struggling with managing the mergeMap observable function in this scenario.
Below is the code snippet of my class :
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse,
HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry';
import 'rxjs/add/operator/mergeMap';
import { of } from 'rxjs';
import { UserService } from '../user/user.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
private token;
constructor(private userService: UserService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.userService.getToken().mergeMap(
(token) => {
request = request.clone({ headers: request.headers.set('Authorization', token) });
return next.handle(request);
}
);
}
}
These are the getToken functions from userService class:
public async getIdToken() {
if (this.getCurrentUser() !== null) {
try {
const session = await this.getCurrentUserSession();
return session.getIdToken().getJwtToken();
} catch (err) {
return Promise.reject(err);
}
} else {
return Promise.reject('No Current User');
}
}
public getToken(): Observable<any> {
return Observable.fromPromise(this.getIdToken());
}