站長資訊網
最全最豐富的資訊網站

深入了解Angular中的路由

什么是路由?本篇文章帶大家深入了解一下Angular中的路由,希望對大家有所幫助!

深入了解Angular中的路由

路由簡介

路由是實現單頁面應用的一種方式,通過監聽hash或者history的變化,渲染不同的組件,起到局部更新的作用,避免每次URL變化都向服務器請求數據。【相關教程推薦:《angular教程》】

路由配置

配置路由模塊: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: 'load',         loadChildren: () => import('./load/load.module').then(m => m.ListModule),         // CanLoadModule如果返回false,模塊里面的子路由都沒有辦法訪問         canLoad: [CanLoadModule]     }, ]

懶加載模塊路由配置:

import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoadComponent } from './Load.component'; import { RouterModule, Routes } from '@angular/router'; import { LoadTwoComponent } from '../../../app/components/LoadTwo/LoadTwo.component'; import { LoadOneComponent } from '../../../app/components/LoadOne/LoadOne.component';  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]="[ 'LoadOne' ]">LoadOne</a> <a [routerLink]="[ 'LoadTwo' ]">LoadTwo</a> <router-outlet></router-outlet>

路由參數傳遞:

const routes: Routes = [     { path: "second/:id", component: SecondComponent }, ]
//routerLinkActive配置路由激活時的類 <a [routerLink]="[ '/second', 12 ]" routerLinkActive="active">second</a>

獲取路由傳遞的參數:

import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { switchMap } from 'rxjs/operators';  @Component({     selector: 'app-second',     templateUrl: './second.component.html',     styleUrls: ['./second.component.scss'] }) 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]="[ '/second', 12 ]">second</a>            // 是可以捕獲到的。上面那種是捕獲不到的。因為不會觸發ngOnInit,公用了一個組件實例。         this.activatedRoute.paramMap.pipe(             switchMap((params: ParamMap) => {                 console.log(params.get('id'));                 return "param";         })).subscribe(() => {          })     }     gotoFirst() {         this.router.navigate(["/first"]);     }  }

queryParams參數傳值,參數獲取也是通過激活的路由的依賴注入

<!-- queryParams參數傳值 --> <a [routerLink]="[ '/first' ]" [queryParams]="{name: 'first'}">first</a>    <!-- ts中傳值 --> <!-- this.router.navigate(['/first'],{ queryParams: { name: 'first' }); -->

路由守衛:canActivate,canDeactivate,resolve,canLoad

路由守衛會返回一個值,如果返回true繼續執行,false阻止該行為,UrlTree導航到新的路由。 路由守衛可能會導航到其他的路由,這時候應該返回false。路由守衛可能會根據服務器的值來 決定是否進行導航,所以還可以返回Promise或 Observable,路由會等待 返回的值是true還是false。 canActivate導航到某路由。 canActivateChild導航到某子路由。

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 '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';  @Injectable({   providedIn: 'root', }) export class AuthGuard implements CanActivate {   canActivate(     next: ActivatedRouteSnapshot,     state: RouterStateSnapshot): any {     // return true;     // 返回Promise的情況     return new Promise((resolve,reject) => {         setTimeout(() => {             resolve(true);         }, 3000);     })   } }
import { Injectable } from '@angular/core'; import {   ActivatedRouteSnapshot,   RouterStateSnapshot,   CanActivateChild } from '@angular/router';  @Injectable({   providedIn: 'root', }) export class AuthGuardChild implements CanActivateChild {   constructor() {}     canActivateChild(     route: ActivatedRouteSnapshot,     state: RouterStateSnapshot): boolean {     return true;   } }

parent.component.html路由導航:

<!-- 使用相對路徑 --> <a [routerLink]="[ './childOne' ]">one</a> <!-- 使用絕對路徑 --> <a [routerLink]="[ '/parent/childTwo' ]">two</a> <router-outlet></router-outlet>

canDeactivate路由離開,提示用戶沒有保存信息的情況。

const routes: Routes = [     { path: "first", component: FirstComponent, canDeactivate: [CanDeactivateGuard] } ]
import { FirstComponent } from './components/first/first.component'; import { RouterStateSnapshot } from '@angular/router'; import { ActivatedRouteSnapshot } from '@angular/router'; import { Injectable } from '@angular/core'; import { CanDeactivate } from '@angular/router';  @Injectable({     providedIn: 'root', }) export class CanDeactivateGuard implements CanDeactivate<any> {     canDeactivate(         component: any,         route: ActivatedRouteSnapshot,         state: RouterStateSnapshot     ): boolean {         // component獲取到組件實例         console.log(component.isLogin);         return true;     } }

canLoad是否能進入懶加載模塊:

const routes: Routes = [     {         path: 'load',         loadChildren: () => import('./load/load.module').then(m => m.LoadModule),         // CanLoadModule如果返回false,模塊里面的子路由都沒有辦法訪問         canLoad: [CanLoadModule]     } ]
import { Route } from '@angular/compiler/src/core'; import { Injectable } from '@angular/core'; import { CanLoad } from '@angular/router';   @Injectable({     providedIn: 'root', }) export class CanLoadModule implements CanLoad {     canLoad(route: Route): boolean {          return true;       } }

resolve配置多久后可以進入路由,可以在進入路由前獲取數據,避免白屏

const routes: Routes = [     { path: "resolve", component: ResolveDemoComponent, resolve: {detail: DetailResolver}  ]
import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';  @Injectable({ providedIn: 'root' }) export class DetailResolver implements Resolve<any> {    constructor() { }    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {     return new Promise((resolve,reject) => {         setTimeout(() => {             resolve("resolve data");         }, 3000);     })   } }

ResolveDemoComponent獲取resolve的值

constructor(private route: ActivatedRoute) { } ngOnInit() {     const detail = this.route.snapshot.data.detail;     console.log(detail); }

監聽路由事件:

constructor(private router: Router) {     this.router.events.subscribe((event) => {         // NavigationEnd,NavigationCancel,NavigationError,RoutesRecognized         if (event instanceof NavigationStart) {             console.log("NavigationStart");         }     }) }

贊(0)
分享到: 更多 (0)
網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
国产视频精品视频| 精品三级AV无码一区| 久久精品国产亚洲av日韩| 麻豆精品国产免费观看| 亚洲精品综合在线影院| 91精品国产麻豆国产自产在线 | 中文字幕一区日韩精品| 国产精品国产国产aⅴ| 日韩精品福利片午夜免费观着| 国产92成人精品视频免费| 999精品视频在线观看| 久久九九国产精品怡红院| 精品国产综合成人亚洲区| 少妇伦子伦精品无吗| 亚洲日韩国产一区二区三区在线 | 亚洲精品无码不卡在线播放| 国产成人精品亚洲日本在线| 91精品国产综合久久青草| 久久久久亚洲精品天堂| 久久水蜜桃亚洲av无码精品麻豆| 久久一区二区精品综合| 久9re热这里精品首页| 无码人妻精品一区二区三区66| 国产精品福利自产拍在线观看| 九九99精品久久久久久| 国产成人精品手机在线观看| 国产成人精品白浆久久69| 久久国产视频精品| 久久青青成人亚洲精品| 日本一区精品久久久久影院 | 99精品视频在线在线视频观看| 日韩人妻无码精品久久免费一| 日韩人妻无码精品一专区| 蜜臀久久99精品久久久久久小说| 亚洲国产精品免费视频| 久久久久99精品成人片试看| 2022久久国产精品免费热麻豆| 精品亚洲AV无码一区二区三区 | 久久丫精品国产亚洲av不卡| 精品一区二区三区在线成人 | 九九久久精品国产AV片国产|