Angular 2 Route Guard逻辑

时间:2017-06-11 18:15:24

标签: angular routes angular2-routing

服务:

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不可访问。

感谢任何见解,谢谢。

1 个答案:

答案 0 :(得分:2)

您应该只将AuthGuard用于需要保护的路由,在您的情况下,它们似乎只是仪表板。 canActivate的内容如下:“如果返回true,则此给定的AuthGuard可以激活此路由。”而不是“这条路线可以激活另一条路线。”所以你可以这样做:

路线

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的链接,以便它可以访问。

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

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