使用AuthGuard进行角度,子级路由

时间:2020-05-17 17:53:27

标签: angular typescript angular-routing

我正在尝试对AuthGaurd使用子路由。

一切似乎都很好:

a)AuthGuard:

canLoad(route: Route): Observable<boolean> {

  return this.authStore.select(selectAuthStatus).pipe(map(response => {
    if (response) {
      return true;
    } else {
      this.router.navigate(['/login']);
    }
  }));
}

它运行良好。

b)每个模块都有子路由:

    const routes = [
        {
            path     : '',
            component: SampleComponent
        }
    ];

@NgModule({
    declarations: [
        SampleComponent
    ],
    imports     : [
        RouterModule.forChild(routes),
...

c)主要路由:

const appRoutes: Routes = [
    { path: 'main', loadChildren: () => import('./main/sample/sample.module').then(m => m.SampleModule) },
    { path: '', loadChildren: () => import('./main/welcome-board/welcome-board.module').then(m => m.WelcomeBoardModule), canLoad: [AuthGuard] },
    {
        path      : '**',
        redirectTo: 'login'
    }
];

d)通过变量在模板中进行路由:

[routerLink]="[item.url]"

该路径有效,但是一直在加载。

1 个答案:

答案 0 :(得分:1)

您应该使用canActivate而不是canLoad:

canActivate(): boolean {
    this.authStore.pipe(select(selectAuthStatus), take(1)).subscribe(response => {
        this.selectorResponse = response;
    });

    if (this.selectorResponse) {
        return true;
    } else {
        this.router.navigate(['/login']);
        return false;
    }
}