I am currently working on a feature to automatically route users to the Login Page when their token expires. However, I am encountering an issue with red lines appearing under certain parts of my code.
return next.handle(_req).do((event: HttpEvent<any>) => {
The problematic lines are here:
this.navCtrl.push('LoginPage');
Below is the full snippet of the code in question:
import { switchMap } from 'rxjs/operators';
import { TokenProvider } from './token/token';
import { Observable } from 'rxjs/Observable';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import {
IonicPage,
NavController,
NavParams,
AlertController,
LoadingController
} from 'ionic-angular';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private tokenProvider: TokenProvider) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return fromPromise(this.tokenProvider.GetToken()).pipe(
switchMap(token => {
const headersConfig = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
if (token) {
headersConfig['Authorization'] = `beader ${token}`;
}
const _req = req.clone({ setHeaders: headersConfig });
return next.handle(_req).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
this.navCtrl.push('LoginPage');
// or show a modal
}
}
});
})
);
}
}
In order to resolve these issues and ensure smooth navigation to the Login Page upon token expiration, what changes should be made to the code?