Angular 9 路由器 - CanActivate 无法使用重定向

问题描述 投票:0回答:2

用例:我想将登录用户重定向到/dashboard,将未登录用户重定向到/landing。

初拍:

  {
    path: '**',
    redirectTo: '/dashboard',
    canActivate: [AuthGuard],
  },
  {
    path: '**',
    redirectTo: '/landing'
  }
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
    return this.auth.isAuthenticated$
  }
}

所有用户都被重定向到仪表板页面。

第二次尝试:

  {
    path: '**',
    redirectTo: '/home/loggedin',
    canActivate: [AuthGuard],
    data: { authGuard: { redirect: '/home/loggedout' } }
  },
  {
    path: '**',
    redirectTo: '/home/loggedin'
  }
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
    return this.auth.isAuthenticated$.pipe(
      map(loggedIn => {
        console.log(`A=${loggedIn} ${JSON.stringify(next.data.authGuard.redirect)}`)
        if (!loggedIn && next.data.authGuard.redirect) {
          return this.router.parseUrl(next.data.authGuard.redirect);
        } else {
          return false;
        }
      })
    );
  }
}

似乎甚至没有调用 AuthGuard。可能如果我使用组件而不是重定向?

  {
    path: '**',
    component: RedirectingComponent,
    canActivate: [AuthGuard],
    data: { authGuard: { redirect: '/home/loggedout' }, redirectComponent: { redirect: '/home/loggedin' } }
  }

现在这似乎可行,但它也是一个糟糕的 hack。

如何使 AuthGuards 与重定向一起工作?

angular angular-router angular-router-guards
2个回答
0
投票

你的

AuthGuard
可以强制导航。在您的第一次尝试中,将守卫更改为这样的东西:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
    // if user is authenticated just return true;
    if (this.auth.isAuthenticated$) { return true; }

    // if user is not authenticated redirect the user and return false
    this.router.navigate(['/landing']);
    return false;
  }
}

这应该将未经身份验证的用户重定向到登录页面。您还可以在角度文档here.

中查看示例

0
投票

您可以使用

children: []
而不是设置
component
(像这样)

{ 
  path: '', 
  canActivate: [AuthGuard], 
  children: [] 
}
© www.soinside.com 2019 - 2024. All rights reserved.