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 in LoginComponent
constructor like
constructor(authService:AuthService){
authService.logout();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.