首页 > 解决方案 > 在注销时为当前路由激活 authguard (Angular)

问题描述

我的 Angular 应用程序有两条带有路线守卫的路线

const routes: Routes = [
  {path: '', component: MenuComponent},
  {path: 'tableChartGFS', canActivate:[AuthGuard] ,component: TableDataChartGfsComponent},
  {path: 'tableAccount', canActivate:[AuthGuard] ,component: TableDataAccountComponent},
  {path: 'auth', component: AuthComponent}
];

路由守卫检查用户当前是否登录(通过检查用户 BehaviorSubject 当前是否为空或设置为用户实例)

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | boolean
    | UrlTree
    | Promise<boolean | UrlTree>
    | Observable<boolean | UrlTree> {
    return this.authService.user.pipe(
      map((user) => {
        const isAuth = !!user;

        if (isAuth) {
          return true;
        }

        return this.router.createUrlTree(['/auth']);
      })
    );
  }
}

当我登录并转到 /tableAccount 路由,然后单击“注销”(将用户 BehaviorSubject 设置为 null)时,我想重定向到主 MenuComponent,因为我不再被允许在此路由上。我怎样才能做到这一点?

标签: angular

解决方案


我通常有一个注销功能来处理注销逻辑,并传递依赖项(路由器、烤面包机、服务等......)像这样的东西

function logout(router: Router, userSrv: userService) { router.navigateByUrl('auth'); userSrv.user.next(undefined); }


推荐阅读