Hello All,
I want to perform some routing operations in Interceptor. How can I use NavController inside Custom Interceptor. Here is sample code of my interceptor:
import { Injectable } from “@angular/core”;
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from “@angular/common/http”;
import { Observable } from “rxjs/Observable”;
import ‘rxjs/add/operator/do’;
import { AppModule } from “…/app/app.module”;
@Injectable()
export class PostInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> {
let postReq =null;
let authenticationToken = localStorage.getItem(‘token’);
if(authenticationToken != null) {
console.log('Authentication Token in interceptor null',authenticationToken);
postReq = req.clone({
headers: req.headers.set('Bearer', authenticationToken).append('Content-Type', 'application/json')
});
}
else{
postReq = req.clone();
}
return next.handle(postReq).do(event => {
if (event instanceof HttpResponse) {
if(event.body.loggedIn != null) {
//loggedIn = false
if(!event.body.loggedIn) {
console.log('Logged In false');
}
else {
//Do Nothing
console.log('LoggedIn True')
}
}
else {
console.log(event.body);
AppModule.map.set('prevRequest',postReq);
}
}
})
}
}
What are you trying to accomplish with AppModule.map?
Please ignore it, It is just caching the request.
I’m not sure what the relation is between your question and your code. I thought your question was interesting. But I don’t understand your code.
Code is doing the following things:
- Adding required headers i.e. if authentication token is present attach it to request’s header.
- While intercepting response if loggedIn property is false then cached that request.
- Now I want to redirect user to login page.
So my question is can I use NavController here?
If you’re lazy loading, you can push or setRoot with any string that is an IonicPage selector. So sure, push whichever page you want onto the nav stack.
I realize there’s a complexity to my answer. You don’t have access to a Nav if you’re in a provider. So if your interceptor is a provider, it needs to send a “go here” message to an active view. You can accomplish this with a subscription in app.component.ts (I’d put it in AfterViewInit.) Then whenever the Subject in your interceptor emits a “go here” message, the Nav in app.component.ts goes there.
I have injected App through construction injection in interceptor. Now able to perform redirection.
Here you go, I have just answered your question you also posted on Stackoverflow:
Hey @lalitkushwah did that solution solve your issue or did you gave up?
Cool, nice to hear it worked 
Could you then now mark this issue and your stackoverflow issue as solved?
Can you show me what you did exactly to fix this? I have the same problem. Thanks
That’s the same stackoverflow post I answered too, funny 
Ha, yea I saw it already answered his question, but figured I would add it if somebody wanted a different option 