0

我在 Angular 7 应用程序中有以下路线。

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='/';
}

现在,当用户在地址栏中键入不存在的 url 时,我想注销用户(使用 中定义的函数auth.service.ts),然后将用户重定向到根 url。

是否可以在路由器本身中执行此函数调用+重定向,而不是编写类似的虚拟组件PageNotFound?我不想有一个额外的组件,因为所有要做的就是,iiuc,在 ngInit 上,它只会调用该logout函数。有什么办法可以做到这一点?

4

1 回答 1

0

由于您已经重定向到LoginComponent所有不匹配的路径,您可以在构造函数中调用您的方法,LoginComponent例如

constructor(authService:AuthService){
authService.logout();
}

演示

于 2019-11-05T07:25:42.283 回答