I have the following routes in an angular 7 app.
app-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
// otherwise redirect to home
{ path: '**', redirectTo: '/login' }
];
auth.service.ts:
func logout() {
this.httpClient.get(config.logoutURL);
window.location.href='/';
}
Now when a user types an non-existent url in the address bar, I want to logout the user (using a function defined in the auth.service.ts
) and then redirect the user to the root url.
Is it possible to do this functioncall+redirection in the router itself, instead of writing a dummy component like PageNotFound
? I do not want to have an extra component, because all that would do is, iiuc, on ngInit, it would just call the logout
function. Any way to achieve this ?
As you'r already redirecting to
LoginComponent
for all unmatched path you can call you method inLoginComponent
constructor likedemo