如何为所有路由根和子路由使用 angular 6 Route Auth Guards? [英] How to use angular 6 Route Auth Guards for all routes Root and Child Routes?

查看:24
本文介绍了如何为所有路由根和子路由使用 angular 6 Route Auth Guards?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为所有路由根和子路由使用 angular 6 Route Auth Guards?

解决方案

1) [创建guard,文件名如auth.guard.ts ]

ng 生成保护身份验证从@angular/core"导入{可注射};导入 { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from'@角度/路由器';从 'rxjs/Observable' 导入 { Observable };从 './auth.service' 导入 { AuthService };从 '@angular/router' 导入 {Router};@Injectable()导出类 AuthGuard 实现 CanActivate {构造函数(私有身份验证:AuthService,私人 myRoute:路由器){}可以激活(下一个:ActivatedRouteSnapshot,状态:RouterStateSnapshot):Observable|Promise<布尔值>|布尔{如果(this.auth.isLoggedIn()){返回真;}别的{this.myRoute.navigate(["登录"]);返回假;}}}

2) 创建以下页面

ng g c login [创建登录页面]ng g c nav [创建导航页面]ng g c home [创建主页]ng g c 注册 [创建注册页面]

3) App.module.ts 文件添加以下内容

import { BrowserModule } from '@angular/platform-b​​rowser';从'@angular/core' 导入 { NgModule };从 '@angular/router' 导入 { RouterModule,Router,Routes };从@angular/forms"导入 { ReactiveFormsModule,FormsModule };从 './auth.service' 导入 { AuthService };从 './auth.guard' 导入 { AuthGuard };从 './app.component' 导入 { AppComponent };从 './login/login.component' 导入 { LoginComponent };从'./nav/nav.component'导入{导航组件};从 './home/home.component' 导入 { HomeComponent };从 './registration/registration.component' 导入 { RegistrationComponent };const myRoots: 路由 = [{ path: '', component: HomeComponent, pathMatch: 'full' , canActivate:[身份验证]},{路径:'注册',组件:注册组件},{ 路径:'登录',组件:登录组件},{ 路径:'home',组件:HomeComponent,canActivate:[AuthGuard]}];@NgModule({声明: [应用组件,登录组件,导航组件,主页组件,注册组件],进口:[BrowserModule,ReactiveFormsModule,FormsModule,RouterModule.forRoot(我的根,{ enableTracing: true }//<-- 仅用于调试目的)],提供者:[AuthService,AuthGuard],引导程序:[AppComponent]})导出类 AppModule { }

4) 在 nav.component.html 中添加链接

<button routerLink="/home">Home</button><button *ngIf="!auth.isLoggedIn()" routerLink="/register">注册</button><button *ngIf="!auth.isLoggedIn()" routerLink="/login">登录</button><button *ngIf="auth.isLoggedIn()" (click)="auth.logout()">注销</button></p>

4.1) 在 nav.component.ts 文件中添加

import { Component, OnInit } from '@angular/core';从 '../auth.service' 导入 { AuthService };@成分({选择器:'app-nav',templateUrl: './nav.component.html',styleUrls: ['./nav.component.css']})导出类 NavComponent 实现 OnInit {构造函数(公共身份验证:AuthService){}ngOnInit() {}}

5) 创建服务页面 在 authservice.ts 中添加以下代码

ng g service auth从@angular/core"导入{可注射};从@angular/router"导入{路由器};@Injectable()导出类 AuthService {构造函数(私有 myRoute:路由器){}发送令牌(令牌:字符串){localStorage.setItem("LoggedInUser", token)}获取令牌(){return localStorage.getItem("LoggedInUser")}isLoggedIn() {返回 this.getToken() !== null;}登出() {localStorage.removeItem("LoggedInUser");this.myRoute.navigate(["登录"]);}}

6) 在 login.ts 中添加内容

import { Component, OnInit } from '@angular/core';从@angular/forms"导入 { FormBuilder, Validators };从@angular/router"导入{路由器};从 '../auth.service' 导入 { AuthService };@成分({选择器:'应用程序登录',templateUrl: './login.component.html',styleUrls: ['./login.component.css']})导出类 LoginComponent 实现 OnInit {形式;构造函数(私人FB:FormBuilder,私有 myRoute:路由器,私人身份验证:AuthService){this.form = fb.group({电子邮件: ['', [Validators.required, Validators.email]],密码:['', Validators.required]});}ngOnInit() {}登录() {如果(this.form.valid){this.auth.sendToken(this.form.value.email)this.myRoute.navigate(["home"]);}}}

6.1) 在 login.component.html 页面中添加

<div><input type="email" placeholder="Email" formControlName="email"/>

<div><input type="password" placeholder="Password" formControlName="password"/>

<button type="submit" color="primary">登录</button></表单>

7) 在 app.component.html 中添加以下代码

<路由器插座></路由器插座>

How to use angular 6 Route Auth Guards for all routes Root and Child Routes ?

解决方案

1) [ Create guard, the file name would be like 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

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

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

<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

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

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

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

<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

<app-nav></app-nav>
<router-outlet></router-outlet>

这篇关于如何为所有路由根和子路由使用 angular 6 Route Auth Guards?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆