ホームページ  >  記事  >  ウェブフロントエンド  >  Angular でのルーティングの詳細

Angular でのルーティングの詳細

青灯夜游
青灯夜游転載
2021-09-07 11:30:062353ブラウズ

ルーティングとは何ですか?この記事では、Angular でのルーティングについて詳しく説明します。お役に立てれば幸いです。

Angular でのルーティングの詳細

ルーティングの概要

ルーティングは、ハッシュをリッスンすることでシングルページ アプリケーションを実装する方法です。または、履歴の変更、さまざまなコンポーネントのレンダリング、ローカル更新の役割を果たし、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>

can情報が保存されていないことをユーザーに通知し、出発ルートを非アクティブ化します。

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 の取得solve の値

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はjuejin.cnで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。