Angular의 라우팅 가드에 대한 자세한 설명

青灯夜游
풀어 주다: 2021-02-22 17:56:00
앞으로
1861명이 탐색했습니다.

이 글에서는 Angular 라우팅의 라우팅 가드를 소개합니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

Angular의 라우팅 가드에 대한 자세한 설명

관련 추천: "angular Tutorial"

1. 경로 가드

사용자가 특정 조건을 충족하면 경로에 들어가거나 탈퇴할 수 있습니다.

경로 보호 시나리오:

사용자가 로그인하고 특정 권한이 있는 경우에만 특정 경로에 들어갈 수 있습니다.

등록 과정 등 여러 양식으로 구성된 마법사입니다. 사용자는 현재 경로의 구성 요소에 필수 정보를 입력해야만 다음 경로로 이동할 수 있습니다.

사용자가 저장 작업을 수행하지 않고 현재 탐색에서 나가려고 하면 사용자에게 경고합니다.

Angular는 경로 진입 또는 이탈을 제어하는 ​​데 도움이 되는 몇 가지 후크를 제공합니다. 이러한 후크는 라우팅 가드이며 위의 시나리오는 이러한 후크를 통해 실현될 수 있습니다.

  • CanActivate: 경로 탐색을 처리합니다.
  • CanDeactivate: 현재 경로에서 출발을 처리합니다.
  • 해결: 라우팅 활성화 전에 라우팅 데이터를 가져옵니다.

일부 속성은 라우팅, 경로, 구성 요소, 콘센트, 하위를 구성할 때 사용되며 라우팅 가드도 라우팅 속성입니다.

2. CanActivate

예: 로그인한 사용자만 제품 정보 라우팅을 입력하도록 허용합니다.

새 가드 디렉터리를 만듭니다. 디렉토리에 새로운 login.guard.ts를 생성하십시오.

LoginGuard 클래스는 CanActivate 인터페이스를 구현하고 true 또는 false를 반환합니다. Angular는 반환 값에 따라 요청의 성공 여부를 결정합니다.

import { CanActivate } from "@angular/router";

export class LoginGuard implements CanActivate{
    canActivate(){
        let loggedIn :boolean= Math.random()<0.5;
        if(!loggedIn){
            console.log("用户未登录");
        }
        return loggedIn;
    }
}
로그인 후 복사

제품 라우팅을 구성하세요. 먼저 공급자에 LoginGuard를 추가한 다음 라우팅 가드를 지정합니다.

canActivate는 여러 가드를 지정할 수 있으며 값은 배열입니다.

const routes: Routes = [
  { path: &#39;&#39;, redirectTo : &#39;home&#39;,pathMatch:&#39;full&#39; }, 
  { path: &#39;chat&#39;, component: ChatComponent, outlet: "aux"},//辅助路由
  { path: &#39;home&#39;, component: HomeComponent },
  { path: &#39;product/:id&#39;, component: ProductComponent, children:[
    { path: &#39;&#39;, component : ProductDescComponent },
    { path: &#39;seller/:id&#39;, component : SellerInfoComponent }
  ] ,canActivate: [LoginGuard]},
  { path: &#39;**&#39;, component: Code404Component }
];
로그인 후 복사

효과: 제품 세부 정보 링크를 클릭하면 콘솔은 사용자에게 로그인되어 있지 않아 제품 세부 정보 경로에 들어갈 수 없다는 것을 알려줍니다.

3. CanDeactivate

출발 시 경로 보호. 떠나기 전에 저장하도록 사용자에게 상기시킵니다.

guard 디렉터리에 새 unsave.guard.ts 파일을 만듭니다.

CanDeactivate 인터페이스에는 현재 구성 요소의 유형을 지정하는 일반 유형이 있습니다.

CanDeactivate 메서드의 첫 번째 매개 변수는 보호할 구성 요소의 상태에 따라 인터페이스에서 지정하는 일반 유형의 구성 요소이거나 사용자가 나갈 수 있는지 여부를 결정하는 메서드를 호출합니다.

import { CanDeactivate } from "@angular/router";
import { ProductComponent } from "../product/product.component";

export class UnsaveGuard implements CanDeactivate<ProductComponent>{
    //第一个参数 范型类型的组件
    //根据当前要保护组件 的状态 判断当前用户是否能够离开
    canDeactivate(component: ProductComponent){
        return window.confirm(&#39;你还没有保存,确定要离开吗?&#39;);
    }
}
로그인 후 복사

경로를 먼저 공급자에 추가한 다음 경로를 구성하세요.

import { NgModule } from &#39;@angular/core&#39;;
import { Routes, RouterModule } from &#39;@angular/router&#39;;
import { HomeComponent } from &#39;./home/home.component&#39;;
import { ProductComponent } from &#39;./product/product.component&#39;;
import { Code404Component } from &#39;./code404/code404.component&#39;;
import { ProductDescComponent } from &#39;./product-desc/product-desc.component&#39;;
import { SellerInfoComponent } from &#39;./seller-info/seller-info.component&#39;;
import { ChatComponent } from &#39;./chat/chat.component&#39;;
import { LoginGuard } from &#39;./guard/login.guard&#39;;
import { UnsaveGuard } from &#39;./guard/unsave.guard&#39;;

const routes: Routes = [
  { path: &#39;&#39;, redirectTo : &#39;home&#39;,pathMatch:&#39;full&#39; }, 
  { path: &#39;chat&#39;, component: ChatComponent, outlet: "aux"},//辅助路由
  { path: &#39;home&#39;, component: HomeComponent },
  { path: &#39;product/:id&#39;, component: ProductComponent, children:[
    { path: &#39;&#39;, component : ProductDescComponent },
    { path: &#39;seller/:id&#39;, component : SellerInfoComponent }
  ] ,canActivate: [LoginGuard],
     canDeactivate: [UnsaveGuard]},
  { path: &#39;**&#39;, component: Code404Component }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [LoginGuard,UnsaveGuard]
})
export class AppRoutingModule { }
로그인 후 복사

효과:

현재 페이지를 떠나려면 확인을 클릭하고, 현재 페이지에 머물려면 취소를 클릭하세요.

4. 가드 해결

http 요청 데이터 반환이 지연되어 템플릿이 즉시 표시되지 않습니다.

데이터가 반환되기 전에 컨트롤러 값을 표시하기 위해 보간 표현식을 사용해야 하는 템플릿의 모든 위치가 비어 있습니다. 사용자 경험이 좋지 않습니다.

해결 방법: 라우팅을 입력하기 전에 서버로 이동하여 데이터를 읽습니다. 필요한 데이터를 모두 읽은 후 데이터와 함께 라우팅을 입력하고 즉시 데이터를 표시합니다.

예:

상품정보 라우팅을 입력하기 전, 상품정보를 준비한 후 라우팅을 입력하세요. 정보를 얻을 수 없거나 정보를 얻는 데 문제가 있는 경우 오류 메시지 페이지로 바로 이동하거나 프롬프트가 팝업되고 더 이상 대상 경로에 진입할 수 없습니다.

먼저 product.comComponent.ts에서 제품 정보 유형을 선언하세요.

export class Product{
  constructor(public id:number, public name:string){
  }
}
로그인 후 복사

guard 디렉터리에 새 product.resolve.ts를 만듭니다. ProductResolve 클래스는 Resolve 인터페이스를 구현합니다.

Resolve는 또한 Resolve로 구문 분석할 데이터 유형인 패러다임을 선언해야 합니다.

import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";

import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Product } from "../product/product.component";

@Injectable()
export class ProductResolve implements Resolve<Product>{

    constructor(private router: Router) {
    }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
        let productId: number = route.params["id"];
        if (productId == 2) { //正确id
            return new Product(1, "iPhone7");
        } else { //id不是1导航回首页
            this.router.navigate(["/home"]);
            return undefined;
        }
    }
}
로그인 후 복사

경로 구성: 공급자에 선언되고 제품 경로에 구성됩니다.

resolve는 객체입니다. 객체에 있는 매개변수의 이름은 전달하려는 매개변수의 이름입니다. 제품은 이를 구문 분석하고 생성하는 데 사용됩니다.

import { NgModule } from &#39;@angular/core&#39;;
import { Routes, RouterModule } from &#39;@angular/router&#39;;
import { HomeComponent } from &#39;./home/home.component&#39;;
import { ProductComponent } from &#39;./product/product.component&#39;;
import { Code404Component } from &#39;./code404/code404.component&#39;;
import { ProductDescComponent } from &#39;./product-desc/product-desc.component&#39;;
import { SellerInfoComponent } from &#39;./seller-info/seller-info.component&#39;;
import { ChatComponent } from &#39;./chat/chat.component&#39;;
import { LoginGuard } from &#39;./guard/login.guard&#39;;
import { UnsaveGuard } from &#39;./guard/unsave.guard&#39;;
import { ProductResolve } from &#39;./guard/product.resolve&#39;;

const routes: Routes = [
  { path: &#39;&#39;, redirectTo : &#39;home&#39;,pathMatch:&#39;full&#39; }, 
  { path: &#39;chat&#39;, component: ChatComponent, outlet: "aux"},//辅助路由
  { path: &#39;home&#39;, component: HomeComponent },
  { path: &#39;product/:id&#39;, component: ProductComponent, children:[
    { path: &#39;&#39;, component : ProductDescComponent },
    { path: &#39;seller/:id&#39;, component : SellerInfoComponent }
  ] ,
    //  canActivate: [LoginGuard],
    //  canDeactivate: [UnsaveGuard],
    resolve:{ //resolve是一个对象
      product : ProductResolve   //想传入product,product由ProductResolve生成
    }},
  { path: &#39;**&#39;, component: Code404Component }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [LoginGuard,UnsaveGuard,ProductResolve]
})
export class AppRoutingModule { }
로그인 후 복사

제품 ID와 이름을 표시하도록 product.comComponent.ts 및 템플릿을 수정하세요.

import { Component, OnInit } from &#39;@angular/core&#39;;
import { ActivatedRoute, Params } from &#39;@angular/router&#39;;

@Component({
  selector: &#39;app-product&#39;,
  templateUrl: &#39;./product.component.html&#39;,
  styleUrls: [&#39;./product.component.css&#39;]
})
export class ProductComponent implements OnInit {

  private productId: number;
  private productName: string;
  constructor(private routeInfo: ActivatedRoute) { }

  ngOnInit() {
    // this.routeInfo.params.subscribe((params: Params)=> this.productId=params["id"]);
    this.routeInfo.data.subscribe(
      (data:{product:Product})=>{
        this.productId=data.product.id;
        this.productName=data.product.name;
      }
    );
  }

}

export class Product{
  constructor(public id:number, public name:string){
  }
}
로그인 후 복사
<div class="product">
  <p>
    这里是商品信息组件
  </p>
  <p>
    商品id是: {{productId}}
  </p>
  <p>
    商品名称是: {{productName}}
  </p>
  
  <a [routerLink]="[&#39;./&#39;]">商品描述</a>
  <a [routerLink]="[&#39;./seller&#39;,99]">销售员信息</a>
  <router-outlet></router-outlet>
</div>
로그인 후 복사

효과:

제품 세부정보 링크를 클릭하면 들어오는 제품 ID는 2이며 이는 리졸브 가드의 올바른 ID이며 제품 데이터 일부가 반환됩니다.

상품상세정보 버튼을 클릭하시면, 들어오는 상품ID가 3번인데, 잘못된 ID이며 홈페이지로 바로 이동됩니다.

이 기사는 다음에서 복제되었습니다: http://www.cnblogs.com/starof/p/9012193.html

프로그래밍 관련 지식을 더 보려면 프로그래밍 비디오를 방문하세요! !

위 내용은 Angular의 라우팅 가드에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:cnblogs.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!