Angular 라우팅에 대해 자세히 알아보기

青灯夜游
풀어 주다: 2021-09-07 11:30:06
앞으로
2372명이 탐색했습니다.

라우팅이란 무엇인가요? 이 글은 여러분에게 Angular 라우팅에 대한 심층적인 이해를 제공할 것입니다. 여러분에게 도움이 되기를 바랍니다!

Angular 라우팅에 대해 자세히 알아보기

라우팅 소개

라우팅은 해시 또는 기록의 변경 사항을 수신하여 다른 구성 요소를 렌더링하고 로컬 업데이트 역할을 하여 매번 변경되지 않도록 합니다. URL 변경. 서버에서 데이터를 요청합니다. [관련 튜토리얼 권장 사항: "angular tutorial"]

Routing 구성

라우팅 모듈 구성: approuter.module.ts

const routes: Routes = [
    { path: "first", component: FirstComponent },
    { path: "parent", component: SecondComponent }
]
@NgModule({
    imports: [
        CommonModule,
        // RouterModule.forRoot方法会返回一个模块,其中包含配置好的Router服务
        // 提供者,以及路由库所需的其它提供者。
        RouterModule.forRoot(routes, {
            // enableTracing: true, // <-- debugging purposes only
            // 配置所有的模块预加载,也就是懒加载的模块,在系统空闲时,把懒加载模块加载进来
            // PreloadAllModules 策略不会加载被CanLoad守卫所保护的特性区。
            preloadingStrategy: PreloadAllModules
          })
    ],
    exports: [
        FirstComponent,
        SecondComponent,
        RouterModule
    ],
    declarations: [
        FirstComponent,
        SecondComponent
    ]
})
export class ApprouterModule { }
로그인 후 복사

app.module.ts에서 수정된 모듈 소개:

imports: [ ApprouterModule ]
로그인 후 복사

방향 라우팅:

const routes: Routes = [
    { path: "", redirectTo: "first", pathMatch: "full" }
]
로그인 후 복사

와일드 카드 라우팅:

const routes: Routes = [
    // 路由器会使用先到先得的策略来选择路由。 由于通配符路由是最不具体的那个,因此务必确保它是路由配置中的最后一个路由。
    { path: "**", component: NotFoundComponent }
]
로그인 후 복사

라우트 레이지 로딩:

레이지 로딩 모듈을 구성하면 레이지 로딩 경로를 클릭하는 경우에만 첫 번째 화면 렌더링이 더 빨라질 수 있습니다. , 해당 모듈이 변경됩니다.

const routes: Routes = [
    {
        path: &#39;load&#39;,
        loadChildren: () => import(&#39;./load/load.module&#39;).then(m => m.ListModule),
        // CanLoadModule如果返回false,模块里面的子路由都没有办法访问
        canLoad: [CanLoadModule]
    },
]
로그인 후 복사

지연 로딩 모듈 라우팅 구성:

import { NgModule } from &#39;@angular/core&#39;;
import { CommonModule } from &#39;@angular/common&#39;;
import { LoadComponent } from &#39;./Load.component&#39;;
import { RouterModule, Routes } from &#39;@angular/router&#39;;
import { LoadTwoComponent } from &#39;../../../app/components/LoadTwo/LoadTwo.component&#39;;
import { LoadOneComponent } from &#39;../../../app/components/LoadOne/LoadOne.component&#39;;

const routes: Routes = [
    {
        path: "",
        component: LoadComponent,
        children: [
            { path: "LoadOne", component: LoadOneComponent },
            { path: "LoadTwo", component: LoadTwoComponent }
        ]
    },

]

@NgModule({
    imports: [
        CommonModule,
        //子模块使用forChild配置
        RouterModule.forChild(routes)
    ],

    declarations: [
        LoadComponent,
        LoadOneComponent,
        LoadTwoComponent
    ]
})
export class LoadModule { }
로그인 후 복사

지연 로딩 모듈 라우팅 탐색:

<a [routerLink]="[ &#39;LoadOne&#39; ]">LoadOne</a>
<a [routerLink]="[ &#39;LoadTwo&#39; ]">LoadTwo</a>
<router-outlet></router-outlet>
로그인 후 복사

라우트 매개변수 전달:

const routes: Routes = [
    { path: "second/:id", component: SecondComponent },
]
로그인 후 복사
rrree

Get 경로 전달된 매개변수:

//routerLinkActive配置路由激活时的类
<a [routerLink]="[ &#39;/second&#39;, 12 ]" routerLinkActive="active">second</a>
로그인 후 복사

queryParams 매개변수는 값으로 전달되며 매개변수 획득도 활성화된 경로의 종속성 주입을 통해 이루어집니다.

import { ActivatedRoute, ParamMap, Router } from &#39;@angular/router&#39;;
import { Component, OnInit } from &#39;@angular/core&#39;;
import { switchMap } from &#39;rxjs/operators&#39;;

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

    constructor(private activatedRoute: ActivatedRoute, private router: Router) { }

    ngOnInit() {

        console.log(this.activatedRoute.snapshot.params);  //{id: "12"}
        // console.log(this.activatedRoute);
        // 这种形式可以捕获到url输入 /second/18 然后点击<a [routerLink]="[ &#39;/second&#39;, 12 ]">second</a>   
        // 是可以捕获到的。上面那种是捕获不到的。因为不会触发ngOnInit,公用了一个组件实例。
        this.activatedRoute.paramMap.pipe(
            switchMap((params: ParamMap) => {
                console.log(params.get(&#39;id&#39;));
                return "param";
        })).subscribe(() => {

        })
    }
    gotoFirst() {
        this.router.navigate(["/first"]);
    }

}
로그인 후 복사

경로 가드: canActivate, canDeactivate, 해결, canLoad

경로 가드는 true가 반환되면 값을 반환합니다. , 실행은 계속됩니다. false는 이 동작을 방지하고 UrlTree는 새 경로로 이동합니다. Route Guard는 다른 경로로 이동할 수 있으며, 이 경우 false를 반환해야 합니다. 경로 가드는 서버의 값에 따라 달라질 수 있습니다. 탐색할지 여부를 결정하면 Promise 또는 Observable도 반환할 수 있으며 경로는 대기합니다. 반환되는 값은 true 또는 false입니다. canActivate는 경로를 탐색합니다. canActivateChild는 하위 경로로 이동합니다.

<!-- queryParams参数传值 -->
<a [routerLink]="[ &#39;/first&#39; ]" [queryParams]="{name: &#39;first&#39;}">first</a>   
<!-- ts中传值 -->
<!-- this.router.navigate([&#39;/first&#39;],{ queryParams: { name: &#39;first&#39; }); -->
로그인 후 복사
const routes: Routes = [
    {
        path: "parent",
        component: ParentComponent,
        canActivate: [AuthGuard],
        children: [
            // 无组件子路由
            {
                path: "",
                canActivateChild: [AuthGuardChild],
                children: [
                    { path: "childOne", component: ChildOneComponent },
                    { path: "childTwo", component: ChildTwoComponent }
                ]
            }
        ],
        // 有组件子路由
        // children: [
        //     { path: "childOne", component: ChildOneComponent },
        //     { path: "childTwo", component: ChildTwoComponent }
        // ]
    }
]
로그인 후 복사
import { Injectable } from &#39;@angular/core&#39;;
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from &#39;@angular/router&#39;;

@Injectable({
  providedIn: &#39;root&#39;,
})
export class AuthGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): any {
    // return true;
    // 返回Promise的情况
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve(true);
        }, 3000);
    })
  }
}
로그인 후 복사

parent.comComponent.html 경로 탐색:

import { Injectable } from &#39;@angular/core&#39;;
import {
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanActivateChild
} from &#39;@angular/router&#39;;

@Injectable({
  providedIn: &#39;root&#39;,
})
export class AuthGuardChild implements CanActivateChild {
  constructor() {}


  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    return true;
  }
}
로그인 후 복사

can탈출 경로를 비활성화하여 사용자에게 정보가 저장되지 않았다는 메시지를 표시합니다.

<!-- 使用相对路径 -->
<a [routerLink]="[ &#39;./childOne&#39; ]">one</a>
<!-- 使用绝对路径 -->
<a [routerLink]="[ &#39;/parent/childTwo&#39; ]">two</a>
<router-outlet></router-outlet>
로그인 후 복사
const routes: Routes = [
    { path: "first", component: FirstComponent, canDeactivate: [CanDeactivateGuard] }
]
로그인 후 복사

canLoad가 지연 로딩 모듈에 들어갈 수 있는지 여부:

import { FirstComponent } from &#39;./components/first/first.component&#39;;
import { RouterStateSnapshot } from &#39;@angular/router&#39;;
import { ActivatedRouteSnapshot } from &#39;@angular/router&#39;;
import { Injectable } from &#39;@angular/core&#39;;
import { CanDeactivate } from &#39;@angular/router&#39;;

@Injectable({
    providedIn: &#39;root&#39;,
})
export class CanDeactivateGuard implements CanDeactivate<any> {
    canDeactivate(
        component: any,
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): boolean {
        // component获取到组件实例
        console.log(component.isLogin);
        return true;
    }
}
로그인 후 복사
const routes: Routes = [
    {
        path: &#39;load&#39;,
        loadChildren: () => import(&#39;./load/load.module&#39;).then(m => m.LoadModule),
        // CanLoadModule如果返回false,模块里面的子路由都没有办法访问
        canLoad: [CanLoadModule]
    }
]
로그인 후 복사

경로 진입을 확인하는 데 얼마나 걸리나요? 흰색 화면을 피하기 위해 경로에 진입하기 전에 데이터를 얻을 수 있습니다.

import { Route } from &#39;@angular/compiler/src/core&#39;;
import { Injectable } from &#39;@angular/core&#39;;
import { CanLoad } from &#39;@angular/router&#39;;


@Injectable({
    providedIn: &#39;root&#39;,
})
export class CanLoadModule implements CanLoad {
    canLoad(route: Route): boolean {

        return true;
      }
}
로그인 후 복사
const routes: Routes = [
    { path: "resolve", component: ResolveDemoComponent, resolve: {detail: DetailResolver} 
]
로그인 후 복사

ResolveDemoComponent의 값을 얻으려면 해결

import { Injectable } from &#39;@angular/core&#39;;
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from &#39;@angular/router&#39;;

@Injectable({ providedIn: &#39;root&#39; })
export class DetailResolver implements Resolve<any> {

  constructor() { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve("resolve data");
        }, 3000);
    })
  }
}
로그인 후 복사

라우팅 이벤트 듣기:

constructor(private route: ActivatedRoute) { }
ngOnInit() {
    const detail = this.route.snapshot.data.detail;
    console.log(detail);
}
로그인 후 복사

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

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

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