Angular Route Guard始终仅重定向到应用程序组件

时间:2019-05-28 06:20:15

标签: angular typescript

我有一个应该在每条路线上都运行的警卫。如果用户已登录,则应将其重定向到其他仪表板进行登录。登录工作正常,但身份验证保护永远不会重定向到仪表板。它总是停留在基本路线上。如果我从后卫手动重定向到仪表板,则会导致无限循环。

app-routes.module.ts

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    children: [
      {
        path: 'dashboard',
        component: DashboardComponent
      },
      {
        path: 'home',
        component: AppComponent
      }
    ]
  },
  {
    path: 'login',
    component: LoginComponent
  }
];

AuthGuard.ts

export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private _router: Router, private _loaderService: LoaderService) {
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    _state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    this._loaderService.show();
    this.authService.isLoggedIn().subscribe( (_allowed: boolean) => {
      if (_allowed) {
        this._loaderService.hide();
        console.info('authenticated', next, _state);
        // this._router.navigate(['/dashboard']); // this cause infinite loop if uncommented
        return true;
      } else {
        console.info('not authenticated');
        this._loaderService.hide();
        this._router.navigate(['/login'], {
          queryParams: {
            return: _state.url
          }
        });
      }
    });
    return false;
  }
}

AuthService.ts

isLoggedIn(): Observable<boolean> {
    if (this.token) {
      return this._httpClient.get(environment.api_url + `/api/auth/` + this.token)
        .pipe(map((_response: any) => {
          this._user.updateUser(_response.data);
          this.updateToken(_response.token);
          return _response.status;
        }));
    } else {
      return of(false);
    }
  }

2 个答案:

答案 0 :(得分:1)

因为您的公共路线不应是受保护路线的子级。

将公共路线移到您的路线的根部,您应该一切顺利。

答案 1 :(得分:0)

也尝试实现CanActivateChild-

canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.canActivate(route, state);
}