Javascript 如何对所有路由根和子路由使用 angular 6 Route Auth Guards?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/50485433/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use angular 6 Route Auth Guards for all routes Root and Child Routes?
提问by Dinesh Ghule
How to use angular 6 Route Auth Guards for all routes Root and Child Routes ?
如何对所有路由根和子路由使用 angular 6 Route Auth Guards?
回答by Kishore Kumar
1) [ Create guard, the file name would be like auth.guard.ts ]
1) [创建守卫,文件名就像 auth.guard.ts ]
ng generate guard auth  
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from 
'@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import {Router} from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService,
    private myRoute: Router){
  }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(this.auth.isLoggedIn()){
      return true;
    }else{
      this.myRoute.navigate(["login"]);
      return false;
    }
  }
}
2) Create below pages
2) 创建以下页面
ng g c login  [Create login page ]
ng g c nav  [Create nav page ]
ng g c home  [Create home page ]
ng g c registration  [Create registration page ]
3) App.module.ts file add below contents
3) App.module.ts 文件添加以下内容
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule,Router,Routes } from '@angular/router';
import { ReactiveFormsModule,FormsModule } from '@angular/forms';
import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { NavComponent } from './nav/nav.component';
import { HomeComponent } from './home/home.component';
import { RegistrationComponent } from './registration/registration.component';
const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' , canActivate: 
  [AuthGuard]},
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];
@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    NavComponent,
    HomeComponent,
    RegistrationComponent
  ],
  imports: [
    BrowserModule,ReactiveFormsModule,FormsModule,
    RouterModule.forRoot(
      myRoots,
      { enableTracing: true } // <-- debugging purposes only
    )
  ],
  providers: [AuthService,AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }
4) Add link in nav.component.html
4) 在 nav.component.html 中添加链接
<p color="primary">
  <button  routerLink="/home">Home</button>
  <button  *ngIf="!auth.isLoggedIn()" routerLink="/register">Register</button>
  <button  *ngIf="!auth.isLoggedIn()" routerLink="/login">Login</button>
  <button  *ngIf="auth.isLoggedIn()" (click)="auth.logout()">Logout</button>
</p>
4.1) Add in nav.component.ts file
4.1) 在 nav.component.ts 文件中添加
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
  constructor(public auth: AuthService) { }
  ngOnInit() {
  }
}
5) Create service page Add below code in authservice.ts
5) 创建服务页面 在 authservice.ts 中添加以下代码
ng g service auth 
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class AuthService {
  constructor(private myRoute: Router) { }
  sendToken(token: string) {
    localStorage.setItem("LoggedInUser", token)
  }
  getToken() {
    return localStorage.getItem("LoggedInUser")
  }
  isLoggedIn() {
    return this.getToken() !== null;
  }
  logout() {
    localStorage.removeItem("LoggedInUser");
    this.myRoute.navigate(["Login"]);
  }
}
6) add content in login.ts
6)在login.ts中添加内容
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  form;
  constructor(private fb: FormBuilder,
    private myRoute: Router,
    private auth: AuthService) {
    this.form = fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }
  ngOnInit() {
  }
  login() {
    if (this.form.valid) {
      this.auth.sendToken(this.form.value.email)
      this.myRoute.navigate(["home"]);
    }
  }
}
6.1) add in login.component.html page
6.1) 在 login.component.html 页面中添加
<form [formGroup]="form" (ngSubmit)="login()">
<div>
<input  type="email" placeholder="Email" formControlName="email" />
</div>
<div>
<input  type="password" placeholder="Password" formControlName="password" />
</div>
<button type="submit" color="primary">Login</button>
</form>
7) Add below code in app.component.html
7) 在 app.component.html 中添加以下代码
<app-nav></app-nav>
<router-outlet></router-outlet>
回答by Roee
https://angular.io/guide/router#canactivate-requiring-authentication
https://angular.io/guide/router#canactivate-requiring-authentication
https://angular.io/guide/router#canactivatechild-guarding-child-routes
https://angular.io/guide/router#canactivatechild-guarding-child-routes
These are really good examples from the Angular.io tutorial "Tour of Heroes" that explain really well authentication for root and child routes.
这些是 Angular.io 教程“英雄之旅”中非常好的示例,它们很好地解释了根路由和子路由的身份验证。

