Reputation: 1042
I am trying to use authguard
and want to navigate to /notfound
url in case of invalid url. Here is my authguard
:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
const self = this;
const userId= route.params.id;
if(!userId){
return false;
}
else{
return from(this.authservice.httpUnauthorizedGet("/api/Users/isUserValid/" + userId)).pipe(
map((data) => {
const dataUpdated: any = data;
if (dataUpdated.allowed === false) {
self.router.navigate(['/notfound']);
return false;
}
return dataUpdated.allowed;
}),
catchError(() => {
self.router.navigate(['/notfound']);
return of(false);
}),
);
}
}
This is working but in case of invalid url (example: /users/1234
), it first navigate to base url( http://localhost:4200
) and then navigate to http://localhost:4200/notfound
.
When I am on /notfound
and I click back, instead on being navigated to /users/1234
, I get navigated to baseurl.
I think this is happening because of return false
. This results in navigating to base url and then router.navigate
navigates to /notfound
.
Is there any way, I can simply be navigated to /notfound
instead of going to base url?
Upvotes: 0
Views: 984
Reputation: 409
Rather then putting 404 navigation logic in AuthenticationGuard.ts
, I let app.routing.ts
handle it. Can you please check out the following code and apply it accordingly if it works for you. For your info the authService I am using is ADAL but that shouldn't be relevant.
authentication.guard.ts
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (this.authService.isLogged) {
return true;
} else {
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.canActivate(childRoute, state);
}
app.routing.ts
const routes: Route[] = [
{ path: 'login', component: LoginComponent },
{ path: 'logout', component: LogoutComponent },
{
path: '', component: MainComponent, canActivate: [ AuthenticationGuard ],
canActivateChild: [ AuthenticationGuard ], children: [
{ path: '', component: MyOwnComponent },
{ path: 'foo', component: FooComponent },
{ path: '**', component: NotFoundComponent }
]
}
]
export const AppRoutes: ModuleWithProviders = RouterModule.forRoot(routes)
The line below is the route that handles 404.
{ path: '**', component: NotFoundComponent }
Upvotes: 1