首頁 web前端 js教程 深入了解Angular中的路由

深入了解Angular中的路由

Sep 07, 2021 am 11:30 AM
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: &#39;load&#39;,
        loadChildren: () => import(&#39;./load/load.module&#39;).then(m => m.ListModule),
        // CanLoadModule如果返回false,模块里面的子路由都没有办法访问
        canLoad: [CanLoadModule]
    },
]
登入後複製
懶載入模組路由設定:

import { NgModule } from &#39;@angular/core&#39;;
import { CommonModule } from &#39;@angular/common&#39;;
import { LoadComponent } from &#39;./Load.component&#39;;
import { RouterModule, Routes } from &#39;@angular/router&#39;;
import { LoadTwoComponent } from &#39;../../../app/components/LoadTwo/LoadTwo.component&#39;;
import { LoadOneComponent } from &#39;../../../app/components/LoadOne/LoadOne.component&#39;;

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]="[ &#39;LoadOne&#39; ]">LoadOne</a>
<a [routerLink]="[ &#39;LoadTwo&#39; ]">LoadTwo</a>
<router-outlet></router-outlet>
登入後複製

路由參數傳遞:

const routes: Routes = [
    { path: "second/:id", component: SecondComponent },
]
登入後複製
//routerLinkActive配置路由激活时的类
<a [routerLink]="[ &#39;/second&#39;, 12 ]" routerLinkActive="active">second</a>
登入後複製

取得路由傳遞的參數:

import { ActivatedRoute, ParamMap, Router } from &#39;@angular/router&#39;;
import { Component, OnInit } from &#39;@angular/core&#39;;
import { switchMap } from &#39;rxjs/operators&#39;;

@Component({
    selector: &#39;app-second&#39;,
    templateUrl: &#39;./second.component.html&#39;,
    styleUrls: [&#39;./second.component.scss&#39;]
})
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]="[ &#39;/second&#39;, 12 ]">second</a>   
        // 是可以捕获到的。上面那种是捕获不到的。因为不会触发ngOnInit,公用了一个组件实例。
        this.activatedRoute.paramMap.pipe(
            switchMap((params: ParamMap) => {
                console.log(params.get(&#39;id&#39;));
                return "param";
        })).subscribe(() => {

        })
    }
    gotoFirst() {
        this.router.navigate(["/first"]);
    }

}
登入後複製

queryParams參數傳值,參數取得也是透過啟動的路由的依賴注入

<!-- queryParams参数传值 -->
<a [routerLink]="[ &#39;/first&#39; ]" [queryParams]="{name: &#39;first&#39;}">first</a>   
<!-- ts中传值 -->
<!-- this.router.navigate([&#39;/first&#39;],{ queryParams: { name: &#39;first&#39; }); -->
登入後複製

路由守衛: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 &#39;@angular/core&#39;;
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from &#39;@angular/router&#39;;

@Injectable({
  providedIn: &#39;root&#39;,
})
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 &#39;@angular/core&#39;;
import {
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanActivateChild
} from &#39;@angular/router&#39;;

@Injectable({
  providedIn: &#39;root&#39;,
})
export class AuthGuardChild implements CanActivateChild {
  constructor() {}


  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    return true;
  }
}
登入後複製
parent.component.html路由導航:
<!-- 使用相对路径 -->
<a [routerLink]="[ &#39;./childOne&#39; ]">one</a>
<!-- 使用绝对路径 -->
<a [routerLink]="[ &#39;/parent/childTwo&#39; ]">two</a>
<router-outlet></router-outlet>
登入後複製

canDeactivate路由離開,提示使用者沒有儲存資訊的情況。 ###
const routes: Routes = [
    { path: "first", component: FirstComponent, canDeactivate: [CanDeactivateGuard] }
]
登入後複製
import { FirstComponent } from &#39;./components/first/first.component&#39;;
import { RouterStateSnapshot } from &#39;@angular/router&#39;;
import { ActivatedRouteSnapshot } from &#39;@angular/router&#39;;
import { Injectable } from &#39;@angular/core&#39;;
import { CanDeactivate } from &#39;@angular/router&#39;;

@Injectable({
    providedIn: &#39;root&#39;,
})
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: &#39;load&#39;,
        loadChildren: () => import(&#39;./load/load.module&#39;).then(m => m.LoadModule),
        // CanLoadModule如果返回false,模块里面的子路由都没有办法访问
        canLoad: [CanLoadModule]
    }
]
登入後複製
import { Route } from &#39;@angular/compiler/src/core&#39;;
import { Injectable } from &#39;@angular/core&#39;;
import { CanLoad } from &#39;@angular/router&#39;;


@Injectable({
    providedIn: &#39;root&#39;,
})
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 &#39;@angular/core&#39;;
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from &#39;@angular/router&#39;;

@Injectable({ providedIn: &#39;root&#39; })
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");
        }
    })
}
登入後複製
###更多程式相關知識,請造訪:###程式設計影片###! ! ###

以上是深入了解Angular中的路由的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何在Ubuntu 24.04上安裝Angular 如何在Ubuntu 24.04上安裝Angular Mar 23, 2024 pm 12:20 PM

Angular.js是一種可自由存取的JavaScript平台,用於建立動態應用程式。它允許您透過擴展HTML的語法作為模板語言,以快速、清晰地表示應用程式的各個方面。 Angular.js提供了一系列工具,可協助您編寫、更新和測試程式碼。此外,它還提供了許多功能,如路由和表單管理。本指南將討論在Ubuntu24上安裝Angular的方法。首先,您需要安裝Node.js。 Node.js是一個基於ChromeV8引擎的JavaScript運行環境,可讓您在伺服器端執行JavaScript程式碼。要在Ub

在Slim框架中實作API路由的方法 在Slim框架中實作API路由的方法 Aug 02, 2023 pm 05:13 PM

在Slim框架中實作API路由的方法Slim是一款輕量級的PHP微型框架,它提供了一個簡單且靈活的方式來建立Web應用程式。其中一個主要功能是實作API路由,使我們能夠將不同的請求對應到對應的處理程序。本文將介紹如何在Slim框架中實作API路由,並提供一些程式碼範例。首先,我們需要安裝Slim框架。可以透過Composer來安裝最新版本的Slim。打開終端機並

使用Angular和Node進行基於令牌的身份驗證 使用Angular和Node進行基於令牌的身份驗證 Sep 01, 2023 pm 02:01 PM

身份驗證是任何網路應用程式中最重要的部分之一。本教程討論基於令牌的身份驗證系統以及它們與傳統登入系統的差異。在本教程結束時,您將看到一個用Angular和Node.js編寫的完整工作演示。傳統身份驗證系統在繼續基於令牌的身份驗證系統之前,讓我們先來看看傳統的身份驗證系統。使用者在登入表單中提供使用者名稱和密碼,然後點擊登入。發出請求後,透過查詢資料庫在後端驗證使用者。如果請求有效,則使用從資料庫中獲取的使用者資訊建立會話,然後在回應頭中傳回會話訊息,以便將會話ID儲存在瀏覽器中。提供用於存取應用程式中受

Java Apache Camel:打造靈活且有效率的服務導向架構 Java Apache Camel:打造靈活且有效率的服務導向架構 Feb 19, 2024 pm 04:12 PM

ApacheCamel是一個基於企業服務匯流排(ESB)的整合框架,它可以輕鬆地將不同的應用程式、服務和資料來源整合在一起,從而實現複雜的業務流程自動化。 ApacheCamel使用基於路由的設定方式,可以輕鬆定義和管理整合流程。 ApacheCamel的主要特點包括:靈活性:ApacheCamel可以輕鬆地與各種應用程式、服務和資料來源整合。它支援多種協議,包括Http、JMS、SOAP、FTP等。高效性:ApacheCamel非常高效,它可以處理大量的訊息。它使用非同步訊息傳遞機制,可以提高效能。可擴

Angular元件及其顯示屬性:了解非block預設值 Angular元件及其顯示屬性:了解非block預設值 Mar 15, 2024 pm 04:51 PM

Angular框架中元件的預設顯示行為不是區塊級元素。這種設計選擇促進了元件樣式的封裝,並鼓勵開發人員有意識地定義每個元件的顯示方式。透過明確設定CSS屬性 display,Angular組件的顯示可以完全控制,從而實現所需的佈局和響應能力。

如何在ThinkPHP6中使用路由 如何在ThinkPHP6中使用路由 Jun 20, 2023 pm 07:54 PM

ThinkPHP6是一款強大的PHP框架,具有便利的路由功能,可輕鬆實現URL路由配置;同時,ThinkPHP6也支援多種路由模式,如GET、POST、PUT、DELETE等等。本文將介紹如何使用ThinkPHP6進行路由設定。一、ThinkPHP6路由模式GET方式:GET方式是用來取得資料的一種方式,常用於頁面展示。在ThinkPHP6中,可以使用如下

如何在Vue專案中使用路由實現頁面切換動畫效果的客製化? 如何在Vue專案中使用路由實現頁面切換動畫效果的客製化? Jul 21, 2023 pm 02:37 PM

如何在Vue專案中使用路由實現頁面切換動畫效果的客製化?引言:在Vue專案中,路由是我們常用的功能之一。透過路由可以實現頁面之間的切換,提供了良好的使用者體驗。而為了讓頁面切換更加生動,我們可以透過客製化動畫效果來實現。本文將介紹如何在Vue專案中使用路由實現頁面切換動畫效果的客製化。建立Vue專案首先,我們需要建立一個Vue專案。可以使用VueCLI來快速搭建

如何在Vue中使用路由實現頁面跳轉? 如何在Vue中使用路由實現頁面跳轉? Jul 21, 2023 am 08:33 AM

如何在Vue中使用路由實現頁面跳轉?隨著前端開發技術的不斷發展,Vue.js已經成為了目前最熱門的前端框架之一。而在Vue開發中,實現頁面跳躍是不可或缺的一部分。 Vue提供了VueRouter來管理應用的路由,透過路由可以實現頁面之間的無縫切換。本文將介紹如何在Vue中使用路由實現頁面跳轉,並附有程式碼範例。首先,在Vue專案中安裝vue-router插件。

See all articles