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

        淺析Angular路由中的懶加載、守衛(wèi)、動態(tài)參數(shù)

        淺析Angular路由中的懶加載、守衛(wèi)、動態(tài)參數(shù)

        路由是將URL請求映射到具體代碼的一種機制,在網(wǎng)站的模塊劃分、信息架構中扮演了重要的角色,而Angular的路由能力非常強大,我們一起來看看吧。【相關教程推薦:《angular教程》】

        路由懶加載

        Angular可以根據(jù)路由,動態(tài)加載相應的模塊代碼,這個功能是性能優(yōu)化的利器。

        為了加快首頁的渲染速度,我們可以設計如下的路由,讓首頁盡量保持簡潔、清爽:

        const routes: Routes = [   {     path: '',     children: [       {         path: 'list',         loadChildren: () => import('./components/list/list.module').then(m => m.ListModule),       },       {         path: 'detail',         loadChildren: () => import('./components/detail/detail.module').then(m => m.DetailModule),       },       ...     ],   }, ];

        首頁只有一些簡單的靜態(tài)元素,而其他頁面,比如列表、詳情、配置等模塊都用loadChildren動態(tài)加載。

        效果如下:

        淺析Angular路由中的懶加載、守衛(wèi)、動態(tài)參數(shù)

        其中的components-list-list-module-ngfactory.js文件,只有當訪問/list路由時才會加載。

        路由守衛(wèi)

        當我們訪問或切換路由時,會加載相應的模塊和組件,路由守衛(wèi)可以理解為在路由加載前后的鉤子,最常見的是進入路由的守衛(wèi)和離開路由的守衛(wèi):

        • canActivate 進入守衛(wèi)
        • canDeactivate 離開守衛(wèi)

        比如我們想在用戶進入詳情頁之前,判斷他是否有權限,就可以使用canActivate守衛(wèi)。

        增加路由守衛(wèi)

        {   path: 'detail',   loadChildren: () => import('./components/detail/detail.module').then(m => m.DetailModule),    // 路由守衛(wèi)   canActivate: [AuthGuard], },

        編寫守衛(wèi)邏輯

        使用CLI命令創(chuàng)建路由守衛(wèi)模塊:

        ng g guard auth

        auth.guard.ts

        import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; import { DetailService } from './detail.service';  @Injectable({   providedIn: 'root' }) export class AuthGuard implements CanActivate {   constructor(     private detailService: DetailService,   ) {}    canActivate(     route: ActivatedRouteSnapshot,     state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {     return new Observable(observer => {       // 鑒權數(shù)據(jù)從后臺接口異步獲取       this.detailService.getDetailAuth().subscribe((hasPermission: boolean) => {         observer.next(hasPermission);         observer.complete();       });     });   } }

        獲取權限service

        獲取權限的service:

        ng g s detail

        detail.service.ts

        import {Injectable} from '@angular/core'; import { HttpClient } from '@angular/common/http';  @Injectable({ providedIn: 'root' }) export class DetailService {   constructor(     private http: HttpClient,   ) { }    getDetailAuth(): any {     return this.http.get('/detail/auth');   } }

        效果如下:

        淺析Angular路由中的懶加載、守衛(wèi)、動態(tài)參數(shù)

        由于我們對/detail路由增加了守衛(wèi),不管是從別的路由切換到/detail路由,還是直接訪問/detail路由,都無法進入該頁面。

        動態(tài)路由參數(shù)

        在路由中帶參數(shù)有很多中方法:

        • 在path中帶參數(shù)
        • 在queryString中帶參數(shù)
        • 不通過鏈接帶參數(shù)

        在path中帶參

        {   path: 'user/:id',   loadChildren: () => import('./components/user/user.module').then(m => m.UserModule), },

        在queryString中帶參數(shù)

        html傳參

        <a [routerLink]="['/list']" [queryParams]="{id: '1'}">...</a>

        ts傳參

        this.router.navigate(['/list'],{ queryParams: { id: '1' });

        通過data傳遞靜態(tài)參數(shù)

        注意:通過data傳遞的路由參數(shù)只能是靜態(tài)的

        {   path: 'detail',   loadChildren: () => import('./components/detail/detail.module').then(m => m.DetailModule),      // 靜態(tài)參數(shù)   data: {     title: '詳情'   } },

        通過resolve傳遞動態(tài)參數(shù)

        data只能傳遞靜態(tài)參數(shù),那我想通過路由傳遞從后臺接口獲取到的動態(tài)參數(shù),該怎么辦呢?

        答案是通過resolve配置。

        {   path: 'detail',   loadChildren: () => import('./components/detail/detail.module').then(m => m.DetailModule),      // 動態(tài)路由參數(shù)   resolve: {     detail: DetailResolver   }, },

        創(chuàng)建Resolver

        detail.resolver.ts

        import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { DetailService } from './detail.service';  @Injectable({ providedIn: 'root' }) export class DetailResolver implements Resolve<any> {    constructor(private detailService: DetailService) { }    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {     return this.detailService.getDetail();   } }

        在服務中增加獲取詳情數(shù)據(jù)的方法

        detail.service.ts

        import {Injectable} from '@angular/core'; import { HttpClient } from '@angular/common/http';  @Injectable({ providedIn: 'root' }) export class DetailService {   constructor(     private http: HttpClient,   ) { }    getDetailAuth(): any {     return this.http.get('/detail/auth');   }    // 增加的   getDetail(): any {     return this.http.get('/detail');   } }

        獲取動態(tài)參數(shù)

        創(chuàng)建組件

        ng g c detial

        detail.component.ts

        import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router';  @Component({   selector: 'app-detail',   templateUrl: './detail.component.html',   styleUrls: ['./detail.component.scss'] }) export class DetailComponent implements OnInit {    constructor(     private route: ActivatedRoute,   ) { }    ngOnInit(): void {     // 和獲取靜態(tài)參數(shù)的方式是一樣的     const detail = this.route.snapshot.data.detail;     console.log('detail:', detail);   }  }

        贊(0)
        分享到: 更多 (0)
        網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號
        主站蜘蛛池模板: 国产精品爽黄69天堂a| 国产精品扒开腿做爽爽爽视频| 2021久久精品国产99国产精品| 日韩精品无码中文字幕一区二区| 久久e热在这里只有国产中文精品99| 93精91精品国产综合久久香蕉| 2023国产精品自拍| 国产在线精品一区二区不卡麻豆| 国产综合精品久久亚洲| 亚洲精品97久久中文字幕无码| 最新国产精品精品视频| 久久九九精品99国产精品| 99久久99这里只有免费的精品| 久久精品成人免费看| 精品国产婷婷久久久| 无码人妻精品一区二区三区夜夜嗨| 99久久精品午夜一区二区| 91久久福利国产成人精品| 一本之道av不卡精品| 国产精品亚洲片在线va| 久久精品国产亚洲精品| 精品国偷自产在线| 91精品国产成人网在线观看| 亚洲精品美女久久久久99小说| 99久久国语露脸精品国产| 欧美日韩国产精品系列| 国产精品人成在线播放新网站| 国产人成精品综合欧美成人| 无码aⅴ精品一区二区三区浪潮| 亚洲国产成人久久精品动漫| 亚洲精品无码国产| 国内精品久久久久久久久| 精品国产粉嫩内射白浆内射双马尾| 国产成人久久久精品二区三区| 四虎影视永久在线观看精品| 国产成人精品怡红院在线观看| 久久精品99久久香蕉国产色戒| 久久精品成人| 91久久福利国产成人精品| 国产精品涩涩涩视频网站| 亚洲国产成人精品女人久久久|