Angular 2 路由守卫逻辑

Angular 2 Route Guard logic

服务:

import { Injectable }     from '@angular/core';
import { CanActivate }    from '@angular/router';
import { Router } from '@angular/router';
import { AngularFireAuth } from 'angularfire2/auth';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private router: Router, public af: AngularFireAuth) { }

  canActivate() {
    this.af.authState.subscribe(res => {
      if (res && res.uid) {
        this.router.navigate(['/dashboard']);
      } else {
        // Prevent user from accessing any route other than /login or /register.
      }
    });
    return true;
  }
}

路由器模块:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AuthGuard } from './auth-guard.service';

import { LoginComponent } from 'app/login/login.component';
import { RegisterComponent } from 'app/register/register.component';
import { DashboardComponent } from 'app/dashboard/dashboard.component';

const appRoutes: Routes = [
  { path: 'login', component: LoginComponent, canActivate:[AuthGuard] },
  { path: 'register', component: RegisterComponent, canActivate:[AuthGuard] },
  { path: 'dashboard', component: DashboardComponent, canActivate:[AuthGuard] },
  { path: '',   redirectTo: '/login', pathMatch: 'full' },
  { path: '**', redirectTo: '/login', pathMatch: 'full' }
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {}

canActivate 函数的作用是重定向用户是否登录。我在路由器模块中的路由上附加了防护装置,但我无法确定下一步的正确逻辑:

如果用户没有登录,他们应该不能访问除/login 或/register 之外的任何路径。当然,我可以在 else 语句中添加 this.router.navigate(['/login']),但这会使 /register 不可访问。

感谢任何见解,谢谢。

您应该只将 AuthGuard 用于需要保护的路由,在您的情况下,这似乎只是仪表板。 canActivate 读起来像: "This given AuthGuard can activate this route, if it returns true." 而不是 "This route can activate another route." 所以你可以这样做:

路线

const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate:[AuthGuard] },
  { path: '',   redirectTo: '/dashboard', pathMatch: 'full' },  
  { path: '**', redirectTo: '/dashboard', pathMatch: 'full' }
];

AuthGuard

@Injectable()
export class AuthGuard implements CanActivate {
  private isLoggedIn = false;

  constructor(private router: Router, public af: AngularFireAuth) {
    af.authState.subscribe(res => this.isLoggedIn = res && res.uid); 
  }

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

有了这个,仪表板将无法访问并在未登录时重定向到 /login。您可以有一个从 LoginComponent 到 RegisterComponent 的 link,这样它就可以访问了。

我猜你有一个登录服务?当登录成功时,该服务可以重定向到仪表板路由。

可在此处找到更多信息:https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard