如果用户已登录,则为Angular 2重定向

Iho*_*huk 5 routing typescript angular

我有这样的路线:

const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
Run Code Online (Sandbox Code Playgroud)

并且AuthGuard:

export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private router: Router,
              private authService: AuthService) { }

  canActivate() {
    if (this.authService.isLoggedIn()) {
      return true;
    }
    this.router.navigate(['login']);
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

当用户访问该网站时,他被重定向到登录页面.当用户尝试访问/dashboard未经身份验证的路由时也会发生相同 /dashboard如果用户已登录,如何将用户重定向到?例如,当我访问myapp.com并且我已登录时,我希望被重定向到myapp.com/dashboard.

fab*_*bbb 12

你想看看resolve[ Routeinterface] 中的属性.

以下所有属性均可用于路径:

export interface Route {
  path?: string;
  pathMatch?: string;
  matcher?: UrlMatcher;
  component?: Type<any>;
  redirectTo?: string;
  outlet?: string;
  canActivate?: any[];
  canActivateChild?: any[];
  canDeactivate?: any[];
  canLoad?: any[];
  data?: Data;
  resolve?: ResolveData;
  children?: Routes;
  loadChildren?: LoadChildren;
  runGuardsAndResolvers?: RunGuardsAndResolvers;
  _loadedConfig?: LoadedRouterConfig;
}
Run Code Online (Sandbox Code Playgroud)

resolve旨在允许您在继续路由之前加载某种类型的数据.签名resolve看起来像这样:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<T>|Promise<T>|T
Run Code Online (Sandbox Code Playgroud)

我们可以忽略该签名,并简单地覆盖它,因为在这种情况下,如果用户登录,我们只想重定向到/ dashboard.否则通常显示/登录路由.

解决方案是创建一个injectable类并将其附加到登录路由的resolve属性.

@Injectable()
export class IsLoggedIn {
  constructor(
    private router: Router, 
    private authService: AuthService) {
  }

  resolve(): void {
    if (this.authService.isAuthenticated) this.router.navigate(['/dashboard'])
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的/登录路由上添加resolve属性.

{
  path: 'login',
  component: LoginComponent,
  resolve: [IsLoggedIn]
}
Run Code Online (Sandbox Code Playgroud)

现在,只要登录用户尝试进入/登录,他们就会被重定向到/ dashboard而不会看到登录页面.


Daw*_*ski 5

在这种情况下,我将一切可能重定向到DashboardComponent使用

{path: '', redirectTo: 'dashboard', pathMatch: 'full'}

并且仪表板组件可以确定用户是否登录(因为它已激活AuthGuard),如果用户未登录,它将重定向他以登录。