I'm using an http interceptor to check for user authentication (JWT, etc.) in Angular 6. My implementation is very similar to what is described here:
Angular HTTP Interceptors - Redirect to Login page and skip further code execution
The interceptor is working great, and I get my login screen as expected. The problem is that before the interceptor redirects to the login screen, it very briefly flashes the route that it's protecting. In other words, for about a millisecond, the route that I'm attempting to protect is displayed, then the interceptor forces the user to the login screen.
I would like to NOT show the protected route at all, even for a millisecond. I understand that "RouteGuard" might be the solution, but I'm hoping for something simpler, which will permit me to guard all routes using the interceptor without specifying a routeguard on every single route.
const appRoutes: Routes = [
{
path: 'homepage',
component: Home
},
{
path: 'login',
component: LoginComponent
}
];
Then, in my auth.interceptor.ts file (not using the whole file, just the relevant part)...
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// we are ok to show the protected route!
}
},
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
this.router.navigate(['/login']);
}
}
});
...
What's happening is that I see the "homepage" route for a very brief moment, then I see the login screen. I don't want to see the homepage route at all, even for a millisecond.
You can protect all your routes with children:
const appRoutes: Routes = [
{
path: 'login',
component: LoginComponent
},
{
path: '',
canActivate: [AuthGuard],
children: [
{
path: 'homepage',
component: Home
}
],
}
];
You can read more at https://angular.io/guide/router#guard-the-admin-feature