如何在Angular中不使用组件使用Guard

3
我的目标是:当点击链接'auth/login/:tokenKey'时,将触发一个方法,然后重定向到A或B组件。对于这个链接'auth/login/:tokenKey',不需要一个组件。它应该只是ts文件中的一个方法。
如何实现?

GetTokenKeyGuard.ts

Original Answer: "最初的回答"
 canActivate(route: ActivatedRouteSnapshot) {

    localStorage.setItem('token_key', route.params.tokenKey);

    return true;
  }

对于路径'auth/login/:tokenKey',我不需要使用组件。在该路径中,会运行一个过程,然后将重定向到索引页面。

但是当我使用'redirectTo'指令时,守卫不起作用。

当我使用组件时,守卫可以正常工作。

如何在没有组件的情况下使用守卫?

app-routing.module.ts

const routes: Routes = [
  { path: '', component: IndexComponent },
  { path: 'auth/login', component: LoginComponent },

  { path: 'auth/login/:tokenKey',
    canActivate: [GetTokenKeyGuard],
    redirectTo: '' }, //........................ Guard doesnt work.

  { path: 'auth/login/:tokenKey',
    canActivate: [GetTokenKeyGuard],
    component: LoginComponent }, //............. Guard works.
];

如果登录失败,您想要重定向到哪里? - Cory Kleiser
实际上,我想在访问'auth/login/:tokenKey'时运行一个方法,然后在该方法中重定向到A组件或B组件... 对于这个链接'auth/login/:tokenKey',不需要一个组件... 帖子已更新。 - canmustu
1个回答

8
您可以使用以下路径
 const routes: Routes = [
  { path: '', component: IndexComponent },
  { path: 'auth/login', component: LoginComponent },

  { path: 'auth/login/:tokenKey',
    canActivate: [GetTokenKeyGuard],
    children: [] }
];



2
children: [] 使得区别明显 :) - Felix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接