您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Angular中路由有什么用,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
路由簡(jiǎn)介
路由是實(shí)現(xiàn)單頁(yè)面應(yīng)用的一種方式,通過(guò)監(jiān)聽hash或者h(yuǎn)istory的變化,渲染不同的組件,起到局部更新的作用,避免每次URL變化都向服務(wù)器請(qǐng)求數(shù)據(jù)。
路由配置
配置路由模塊:approuter.module.ts
const routes: Routes = [ { path: "first", component: FirstComponent }, { path: "parent", component: SecondComponent } ] @NgModule({ imports: [ CommonModule, // RouterModule.forRoot方法會(huì)返回一個(gè)模塊,其中包含配置好的Router服務(wù) // 提供者,以及路由庫(kù)所需的其它提供者。 RouterModule.forRoot(routes, { // enableTracing: true, // <-- debugging purposes only // 配置所有的模塊預(yù)加載,也就是懶加載的模塊,在系統(tǒng)空閑時(shí),把懶加載模塊加載進(jìn)來(lái) // 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ì)使用先到先得的策略來(lái)選擇路由。 由于通配符路由是最不具體的那個(gè),因此務(wù)必確保它是路由配置中的最后一個(gè)路由。 { path: "**", component: NotFoundComponent } ]
路由懶加載:
配置懶加載模塊可以使得首屏渲染速度更快,只有點(diǎn)擊懶加載路由的時(shí)候,對(duì)應(yīng)的模塊才會(huì)更改。
const routes: Routes = [ { path: 'load', loadChildren: () => import('./load/load.module').then(m => m.ListModule), // CanLoadModule如果返回false,模塊里面的子路由都沒(méi)有辦法訪問(wèn) 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ù)獲取也是通過(guò)激活的路由的依賴注入
<!-- 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ù)器的值來(lái) 決定是否進(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: [ // 無(wú)組件子路由 { 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)航:
<!-- 使用相對(duì)路徑 --> <a [routerLink]="[ './childOne' ]">one</a> <!-- 使用絕對(duì)路徑 --> <a [routerLink]="[ '/parent/childTwo' ]">two</a> <router-outlet></router-outlet>
canDeactivate路由離開,提示用戶沒(méi)有保存信息的情況。
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,模塊里面的子路由都沒(méi)有辦法訪問(wèn) 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"); } }) }
關(guān)于“Angular中路由有什么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。