
在Angular 中,路由是以模块为单位的,每个模块都可以有自己的路由。 [関連チュートリアルの推奨事項:「angular チュートリアル」]
1. ルーティング用のページコンポーネント、レイアウトコンポーネント、ナビゲーションコンポーネントを作成します。
Create the home page component ng gc pages/home
Create the about us page component ng gc pages/about
Create the layout component ng gc pages/layout
Create the navigation component ng gc pages/navigation
2. Create routing rules
// app.module. ts
import { Routes } from "@angular/router"
const routes: Routes = [
{
パス: 「ホーム」、
コンポーネント:ホームコンポーネント
}、
{
path: "about",
コンポーネント:コンポーネントについて
}
] 3. ルーティングモジュールを導入し、
// app.module.tsを開始します。
import { RouterModule, Routes } from "@angular/router"
@ngmodule({
インポート: [RouterModule.forRoot(routes, { useHash: true })],
})
export class appmodule {} 4。路由插座
<! - ルーティングソケットを追加します。つまり、プレースホルダーコンポーネントに一致するルーティングコンポーネントがここに表示されます - > <router-outlet></router-outlet>5.
ナビゲーション コンポーネントで
リンク<a routerLink="/home">ホームページ</a>を定義します。
<a routerLink="/about">会社概要</a>
1.リダイレクト
const ルート: ルート = [
{
path: "home",
コンポーネント:ホームコンポーネント
}、
{
パス:「アバート」、
コンポーネント:コンポーネントについて
}、
{
パス: ""、
// リダイレクト redirectTo: "home",
// 完全匹配pathMatch: "full"
}
] 2. 404 ページの
const ルート: Routes = [
{
パス:「ホーム」、
コンポーネント:ホームコンポーネント
}、
{
パス: "約"、
コンポーネント:コンポーネントについて
}、
{
パス: "**"、
コンポーネント: NotFoundComponent
}
]1. クエリパラメータ
<a routerLink="/about" [queryParams]="{ name: 'kitty' }">会社概要</a> import { ActivatedRoute } from "@angular/router"
エクスポート クラス AboutComponent は OnInit を実装します {
コンストラクター(プライベート ルート: ActivatedRoute) {}
ngOnInit(): void {
this.route.queryParamMap.subscribe(query => {
query.get("名前")
})
}
2.動的パラメータ
const Routes: Routes = [
{
パス: 「ホーム」、
コンポーネント:ホームコンポーネント
}、
{
パス: "about/:name",
コンポーネント:コンポーネントについて
}
] <a [routerlink] = "['/about'、 'zhangsan']"> about us </a>
「@angular/router」から{activatedRoute}をインポート
エクスポート クラス AboutComponent は OnInit を実装します {
コンストラクター(プライベート ルート: ActivatedRoute) {}
ngOnInit(): void {
this.route.paramMap.subscribe(params => {
params.get("name")
})
}
ルート路由嵌套指的是如何定义子级路由。
const ルート: ルート = [
{
path: "about",
コンポーネント: コンポーネントについて、
子供たち: [
{
path: "introduce",
コンポーネント:紹介コンポーネント
}、
{
path: "history",
コンポーネント:HistoryComponent
}
】
}
] <! - about.component.html->
<app-layout>
<p>about works!</p>
<a routerLink="/about/introduce">公司简介</a>
<a routerLink="/about/history">開発履歴</a>
<div>
<router-outlet> </router-outlet>
</div>
</app-layout>ソケットに名前を付けます
チャイルドルーティングコンポーネントをさまざまなルーティングアウトレットに露出させます。
{
path: "about",
component: AboutComponent,
子供たち: [
{
パス: "紹介",
コンポーネント: 導入コンポーネント、
アウトレット:「左」
}、
{
パス:「歴史」、
コンポーネント: 履歴コンポーネント、
アウトレット:「正しい」
}
】
< !
-- about.component.html --> <アプリのレイアウト> <p>作品について!</p> <ルーターアウトレット名="左"></ルーターアウトレット> <router-outlet name = "right"> </router-outlet> </app-layout>
<a
[ルーターリンク]=[
'/について'、
{
アウトレット:{
left: ['introduce'],
right: ['history']
}
}
]」
>私たちについて</a><! - app.component.html-> <button(click)= "jump()">開発履歴にジャンプ</button>
// app.component.ts
import { Router } from "@angular/router"
エクスポート クラス HomeComponent {
コンストラクター(プライベートルーター: Router) {}
jump() {
this.router.navigate(["/about/history"], {
queryParams: {
name: "Kitty"
}
})
}
}ルートモジュールのルーティング構成を、根路由模块と呼ばれる別のルーティングモジュールに抽象化し、ルートルーティングモジュールをルートモジュールに導入します。
「@angular/core」から { NgModule } をインポートします
import { HomeComponent } from "./pages/home/home.component"
import { NotFoundComponent } from "./pages/not-found/not-found.component"
const routes: Routes = [
{
パス: ""、
component: HomeComponent
}、
{
パス: "**"、
コンポーネント: NotFoundComponent
}
】
@NgModule({
declarations: [],
インポート: [RouterModule.forRoot(routes, { useHash: true })],
// angularルーティング関数モジュールをエクスポートします。これは、ルーミジュールモジュールで提供されるルーティングソケットコンポーネントがルートモジュールエクスポートのルートコンポーネントで使用されているためです。
})
import class AppRoutingModule {} import { BrowserModule } from "@angular/platform-browser"
「@angular/core」から { NgModule } をインポートします
{AppComponent} を「./app.component」からインポートします
"./app-routing.module"から{approutingmodule}をインポート
"./pages/home/home.component"から{HomeComponent}をインポート
import { NotFoundComponent } from "./pages/not-found/not-found.component"
@NgModule({
declarations: [AppComponent,HomeComponent, NotFoundComponent],
輸入:[BrowsModule、AppRoutingModule]、
プロバイダー: []、
ブートストラップ: [AppComponent]
})
export class AppModule {}ルートの遅延読み込みは模块に基づいています。
1.ユーザーモジュールng gm user --routing=trueとこのモジュールのルーティングモジュールを一緒に作成し
ng gc user/pages/register
ng gc user/pages/login
ng gc user/pages/register
4。ユーザーモジュールの構成ルーティングルールは
、「@angular/core」から{ngmodule}をインポートします
import { Routes, RouterModule } from "@angular/router"
"./pages/login/login.component"から{logincomponent}をインポート
"./pages/register/register.component"から{RegisterComponent}をインポート
constルート:ルート= [
{
パス: "ログイン"、
コンポーネント: ログインコンポーネント
}、
{
パス: "登録",
コンポーネント: レジスタコンポーネント
}
】
@NgModule({
インポート: [RouterModule.forChild(routes)]、
エクスポート: [ルーターモジュール]
})
userroutingmodule {} 5。ユーザールーティングモジュールをメインルーティングモジュールに関連付ける
// app-routing.module.ts
const ルート: ルート = [
{
パス: "ユーザー"、
loadChildren:()=> import( "./ user/user.module")。
}
] 6.アクセスリンクを追加<a routerlink = "/user/login"> login </a>
ナビゲーションコンポーネントに
<a routerlink = "/user/register">レジスタ</a>
ルート ガードは、要求されたルートへのナビゲーションが許可されているかどうかをルートに伝えます。
ルートガードメソッドは、 booleanまたはObservable <boolean>またはPromise <boolean>を返すことができます。これは、将来のある時点でブール値に解決します。
1. CanActivate は、
是否可以访问某一个路由確認します。
CanActivate为接口、ルート ガード クラスはこのインターフェイスを実装する必要があります。このインターフェイスは、クラスがターゲット ルートへのアクセスを許可するかどうかを決定する canActivate メソッドを持つ必要があることを規定します。
路由可以应用多个守卫,所有守卫方法都允许,路由才被允许访问,有一个守卫方法不允许,则路由不允许被访问。
ルート ガードの作成: ng g guard guards/auth
import { Injectable } from "@angular/core"
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from "@angular/router"
「rxjs」から{Observable}をインポート
@Injectable({
供給:「ルート」
})
export class AuthGuard implements CanActivate {
コンストラクター(プライベートルーター:ルーター){}
canActivate(): boolean | UrlTree {
// ジャンプの実装に使用 return this.router.createUrlTree(["/user/login"])
// ターゲットルートへのアクセスを無効にします return false
// 允许访问目标路由return true
}
} {
パス:「アバート」、
component: AboutComponent,
canActivate: [AuthGuard]
2. CanActivateChild は、
ユーザーが特定のサブルートにアクセスできるかどうかを確認します。
创建路由守卫: ng g guard guards/admin注意:选择CanActivateChild,需要将箭头移动到这个选项并且敲击空格确认选择。
「@angular/core」から{injectable}をインポート
Import {canactivateChild、activatedRoutesNapshot、routerStateSnapshot、urltree} from "@angular/router"
import { Observable } from "rxjs"
@Injectable({
指定: "ルート"
})
輸出クラスのアドミンガードは、canactivatechildを実装しています{
canactivatechild():boolean |
trueを返す
}
} {
パス:「アバート」、
コンポーネント:概要、
canactivatechild:[adminguard]、
子供たち: [
{
パス: "紹介",
コンポーネント: コンポーネントの紹介
}
】
} 3、CanDeactivate
检查用户是否可以退出路由。
たとえば、フォームでユーザーが入力したコンテンツが保存されず、ユーザーがルートを離れたい場合、ガードを呼び出してユーザーに促すことができます。
import { Injectable } from "@angular/core"
輸入 {
Candeactivate、
ActivatedRoutesNapshot、
routerstatesnapshot、
URLツリー
} from "@angular/router"
「rxjs」から{Observable}をインポート
エクスポートインターフェイス CanComponentLeave {
canLeave: () => ブール値
}
@Injectable({
供給:「ルート」
})
エクスポート クラス UnsaveGuard は CanDeactivate<CanComponentLeave> {を実装します。
Candeactivate(コンポーネント:CanComponentLeave):boolean {
if(component.canleave()){
trueを返す
}
falseを返す
}
} {
パス: ""、
component: HomeComponent,
canDeactivate: [UnsaveGuard]
} 「src/app/guards/unsave.guard」から{cancomponentLeave}をimport
輸出クラスの故郷はCanComponentLeaveを実装しています{
myForm: FormGroup = new FormGroup({
username: new FormControl()
})
canLeave(): boolean {
if (this.myForm.dirty) {
if(window.confirm( "保存されていないデータがありますが、去りたいですか?")){
trueを返す
} それ以外 {
falseを返す
}
}
trueを返す
} 4. Resolve を使用する
と、ルーティングに入る前にデータを取得し、データの取得が完了した後にルーティングに入ることができます。
ng g resolver <name>
import { Injectable } from "@angular/core"
import { Resolve } from "@angular/router"
type returnType = promise <{name:string}>
@Injectable({
指定: "ルート"
})
エクスポート クラス ResolveGuard は Resolve<returnType> {を実装します
Resolve():returnType {
新しい約束を返す(function(resolve){
setimeout(()=> {
solve({ 名前: "張三" })
}、2000)
})
}
} {
パス: ""、
コンポーネント:ホームコンポーネント、
解決する: {
ユーザー:ResolveGuard
}
}クラスのホームコンポーネントをエクスポート{
コンストラクター(プライベートルート:ActivatedRoute){}
ngOnInit(): void {
console.log(this.route.snapshot.data.user)
}
}