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

        深入了解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麻豆网站| 亚洲国产精品成人久久蜜臀| 国产精品亚洲精品| 亚洲国产精品成人| 精品国产亚洲一区二区在线观看 | 青青久久精品国产免费看 | 国产午夜精品一区二区三区漫画| 久久久久99精品成人片牛牛影视| 2021最新国产精品一区| 国产精品久久久久国产A级| 亚洲av午夜福利精品一区人妖| 久久国产精品二国产精品| 久久国产精品-久久精品| 国内精品久久人妻互换| 亚洲av成人无码久久精品| 亚洲福利精品电影在线观看| 久久99精品国产麻豆婷婷| 99久久国产热无码精品免费久久久久 | 日韩一区二区三区精品| 国产欧美日韩精品专区| 粉嫩精品美女国产在线观看| 久久这里只有精品久久| 大桥未久在线精品视频在线| 国产精品久久午夜夜伦鲁鲁| 精品午夜福利在线观看| 久久精品www人人爽人人| 无码精品A∨在线观看中文| 亚洲国产精品无码成人片久久| 一本大道无码日韩精品影视| 日韩精品无码Av一区二区| 老司机精品影院91| 欧美日韩精品一区二区三区不卡 | 国产一区二区精品久久岳| 国产国产成人久久精品| 99热成人精品免费久久| 高清在线国产午夜精品| 国产精品一区12p| 精品午夜国产人人福利| 久久久久人妻一区精品果冻| 日本精品一区二区三区在线视频 |