站長資訊網(wǎng)
        最全最豐富的資訊網(wǎng)站

        深入了解Angular中的路由

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

        深入了解Angular中的路由

        路由簡介

        路由是實(shí)現(xiàn)單頁面應(yīng)用的一種方式,通過監(jiān)聽hash或者h(yuǎn)istory的變化,渲染不同的組件,起到局部更新的作用,避免每次URL變化都向服務(wù)器請求數(shù)據(jù)。【相關(guān)教程推薦:《angular教程》】

        路由配置

        配置路由模塊:approuter.module.ts

        const routes: Routes = [     { path: "first", component: FirstComponent },     { path: "parent", component: SecondComponent } ] @NgModule({     imports: [         CommonModule,         // RouterModule.forRoot方法會(huì)返回一個(gè)模塊,其中包含配置好的Router服務(wù)         // 提供者,以及路由庫所需的其它提供者。         RouterModule.forRoot(routes, {             // enableTracing: true, // <-- debugging purposes only             // 配置所有的模塊預(yù)加載,也就是懶加載的模塊,在系統(tǒng)空閑時(shí),把懶加載模塊加載進(jìn)來             // PreloadAllModules 策略不會(huì)加載被CanLoad守衛(wèi)所保護(hù)的特性區(qū)。             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 = [     // 路由器會(huì)使用先到先得的策略來選擇路由。 由于通配符路由是最不具體的那個(gè),因此務(wù)必確保它是路由配置中的最后一個(gè)路由。     { path: "**", component: NotFoundComponent } ]

        路由懶加載:

        配置懶加載模塊可以使得首屏渲染速度更快,只有點(diǎn)擊懶加載路由的時(shí)候,對應(yīng)的模塊才會(huì)更改。

        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 { }

        懶加載模塊路由導(dǎo)航:

        <a [routerLink]="[ 'LoadOne' ]">LoadOne</a> <a [routerLink]="[ 'LoadTwo' ]">LoadTwo</a> <router-outlet></router-outlet>

        路由參數(shù)傳遞:

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

        獲取路由傳遞的參數(shù):

        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 然后點(diǎn)擊<a [routerLink]="[ '/second', 12 ]">second</a>            // 是可以捕獲到的。上面那種是捕獲不到的。因?yàn)椴粫?huì)觸發(fā)ngOnInit,公用了一個(gè)組件實(shí)例。         this.activatedRoute.paramMap.pipe(             switchMap((params: ParamMap) => {                 console.log(params.get('id'));                 return "param";         })).subscribe(() => {          })     }     gotoFirst() {         this.router.navigate(["/first"]);     }  }

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

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

        路由守衛(wèi):canActivate,canDeactivate,resolve,canLoad

        路由守衛(wèi)會(huì)返回一個(gè)值,如果返回true繼續(xù)執(zhí)行,false阻止該行為,UrlTree導(dǎo)航到新的路由。 路由守衛(wèi)可能會(huì)導(dǎo)航到其他的路由,這時(shí)候應(yīng)該返回false。路由守衛(wèi)可能會(huì)根據(jù)服務(wù)器的值來 決定是否進(jìn)行導(dǎo)航,所以還可以返回Promise或 Observable,路由會(huì)等待 返回的值是true還是false。 canActivate導(dǎo)航到某路由。 canActivateChild導(dǎo)航到某子路由。

        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路由導(dǎo)航:

        <!-- 使用相對路徑 --> <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獲取到組件實(shí)例         console.log(component.isLogin);         return true;     } }

        canLoad是否能進(jìn)入懶加載模塊:

        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配置多久后可以進(jìn)入路由,可以在進(jìn)入路由前獲取數(shù)據(jù),避免白屏

        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); }

        監(jiān)聽路由事件:

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

        贊(0)
        分享到: 更多 (0)
        網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號
        主站蜘蛛池模板: 久久久久久无码国产精品中文字幕 | 精品人妻大屁股白浆无码| 久久97精品久久久久久久不卡| 亚洲性日韩精品一区二区三区| 国产精品极品| 久久99精品国产99久久| 亚洲精品中文字幕无码蜜桃| 久久99精品久久久久久秒播 | 亚洲无码精品浪潮| 看99视频日韩精品| 国产精品一级毛片无码视频| 久久精品视频免费| 国产精品欧美日韩| 97久久久精品综合88久久| 精品欧洲av无码一区二区三区| 亚洲精品无码99在线观看 | 亚洲高清国产AV拍精品青青草原| 精品人妻V?出轨中文字幕| 国产成人精品久久亚洲高清不卡 | 国产精品成人在线| 国产亚洲精品资源在线26u| 人妻精品久久久久中文字幕69 | 91精品国产麻豆国产自产在线| 国产91精品在线| 国产精品多p对白交换绿帽| 久久精品亚洲中文字幕无码麻豆| 亚洲一区二区三区国产精品| 亚洲av午夜国产精品无码中文字 | 国产精品自产拍在线观看花钱看| 97久久精品人人做人人爽| 四虎在线精品视频一二区| 久久99精品国产| 51精品资源视频在线播放| 囯产精品一区二区三区线| 国产精品日韩欧美久久综合| 国产香蕉精品视频在| 国产原创精品视频| 在线观看日韩精品| 国产精品福利片免费看 | 91精品国产色综久久| 国产成人精品一区在线|