ホームページ  >  記事  >  ウェブフロントエンド  >  Angular でのルーティングの詳細と、すぐに始める方法について学びましょう。

Angular でのルーティングの詳細と、すぐに始める方法について学びましょう。

青灯夜游
青灯夜游転載
2021-09-24 11:05:401647ブラウズ

この記事では、Angular でのルーティングを深く理解し、すぐに始める方法を見て、マッチング ルール、ルーティング パラメーター、ルーティングのネスティング、ルーティング ガードなどを紹介します。誰にとっても役に立つでしょう。役に立ちました!

Angular でのルーティングの詳細と、すぐに始める方法について学びましょう。

Angular では、ルーティングはモジュールに基づいており、各モジュールは独自のルートを持つことができます。 [関連チュートリアルの推奨事項: "angular チュートリアル"]

すぐに始めましょう

ページ コンポーネント、Layout コンポーネント、およびNavigation コンポーネント、ルーティングに使用されます

  • CreateHomepagePage コンポーネントng g c pages/home

  • 作成会社概要ページ コンポーネントng g c pages/about

  • ##作成

    レイアウトコンポーネントng g c ページ/レイアウト

  • 作成

    ナビゲーションコンポーネントng g c ページ/ナビゲーション

  • #ルーティング ルールの作成
// app.module.ts
import { Routes } from "@angular/router"

const routes: Routes = [
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "about",
    component: AboutComponent
  }
]

ルーティング モジュールを導入して開始

// app.module.ts
import { RouterModule, Routes } from "@angular/router"

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
})
export class AppModule {}

ルーティング ソケットを追加

<!-- 路由插座即占位组件 匹配到的路由组件将会显示在这个地方 -->
<router-outlet></router-outlet>

ナビゲーション コンポーネントでリンクを定義

<a routerLink="/home">首页</a>
<a routerLink="/about">关于我们</a>

一致ルール

1、リダイレクト

const routes: Routes = [
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "about",
    component: AboutComponent
  },
  {
    path: "",
    // 重定向
    redirectTo: "home",
    // 完全匹配
    pathMatch: "full"
  }
]

2、<span style="font-size: 16px;"></span>404<span style="font-size: 16px;"></span> ページ<span style="font-size: 16px;"></span>

const routes: Routes = [
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "**",
    component: NotFoundComponent
  }
]
ルート パラメータ

1. クエリ パラメータ<span style="font-size: 16px;"></span>
<a routerLink="/about" [queryParams]="{ name: &#39;kitty&#39; }">关于我们</a>
import { ActivatedRoute } from "@angular/router"

export class AboutComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.route.queryParamMap.subscribe(query => {
      query.get("name")
    })
  }
}

2. 動的パラメータ<span style="font-size: 16px;"></span>

const routes: Routes = [
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "about/:name",
    component: AboutComponent
  }
]
<a [routerLink]="[&#39;/about&#39;, &#39;zhangsan&#39;]">关于我们</a>
import { ActivatedRoute } from "@angular/router"

export class AboutComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
      params.get("name")
    })
  }
}

ルーティングのネスト

ルーティングのネストとは、サブレベルを定義する方法を指します。ルーティング

const routes: Routes = [
  {
    path: "about",
    component: AboutComponent,
    children: [
      {
        path: "introduce",
        component: IntroduceComponent
      },
      {
        path: "history",
        component: 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,
  children: [
    {
      path: "introduce",
      component: IntroduceComponent,
      outlet: "left"
    },
    {
      path: "history",
      component: HistoryComponent,
      outlet: "right"
    }
  ]
}
<!-- about.component.html -->
<app-layout>
  <p>about works!</p>
  <router-outlet name="left"></router-outlet>
  <router-outlet name="right"></router-outlet>
</app-layout>

ナビゲーション ルーティング

<a
    [routerLink]="[
      &#39;/about&#39;,
      {
        outlets: {
          left: [&#39;introduce&#39;],
          right: [&#39;history&#39;]
        }
      }
    ]"
>关于我们</a>
<!-- app.component.html -->
<button (click)="jump()">跳转到发展历史</button>

ルーティングmodule

ルート モジュールのルーティング設定をルート ルーティング モジュールと呼ばれる別のルーティング モジュールに抽象化し、ルート ルーティング モジュールをルート モジュールに導入します

// app.component.ts
import { Router } from "@angular/router"

export class HomeComponent {
  constructor(private router: Router) {}
  jump() {
    this.router.navigate(["/about/history"], {
      queryParams: {
        name: "Kitty"
      }
    })
  }
}
import { NgModule } from "@angular/core"

import { HomeComponent } from "./pages/home/home.component"
import { NotFoundComponent } from "./pages/not-found/not-found.component"

const routes: Routes = [
  {
    path: "",
    component: HomeComponent
  },
  {
    path: "**",
    component: NotFoundComponent
  }
]

@NgModule({
  declarations: [],
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  // 导出 Angular 路由功能模块,因为在根模块的根组件中使用了 RouterModule 模块中提供的路由插座组件
  exports: [RouterModule]
})
export class AppRoutingModule {}

ルーティング遅延読み込み

ルーティングの遅延読み込みはモジュールに基づいています。

    ユーザー モジュールの作成
  • ng g m user --routing=true

    とこのモジュールのルーティング モジュールの作成

  • Createログイン ページ コンポーネント
  • ng g c user/pages/login

  • 登録ページ コンポーネントの作成
  • ng g c user/pages/register

  • ユーザー モジュールのルーティング ルールを構成する
  • import { BrowserModule } from "@angular/platform-browser"
    import { NgModule } from "@angular/core"
    import { AppComponent } from "./app.component"
    import { AppRoutingModule } from "./app-routing.module"
    
    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule, AppRoutingModule],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    ユーザー ルーティング モジュールをメイン ルーティング モジュールに関連付ける
  • import { NgModule } from "@angular/core"
    import { Routes, RouterModule } from "@angular/router"
    import { LoginComponent } from "./pages/login/login.component"
    import { RegisterComponent } from "./pages/register/register.component"
    
    const routes: Routes = [
      {
        path: "login",
        component: LoginComponent
      },
      {
        path: "register",
        component: RegisterComponent
      }
    ]
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule]
    })
    export class UserRoutingModule {}

  • ナビゲーション コンポーネントにアクセス リンクを追加します
  • // app-routing.module.ts
    const routes: Routes = [
      {
        path: "user",
        loadChildren: () => import("./user/user.module").then(m => m.UserModule)
      }
    ]

  • ルート ガード

ルート ガードは、要求されたルートへのナビゲーションが可能かどうかをルートに伝えます。許可された。

ルート ガード メソッドは、

boolean

または Observable \803a2f0672c4eeec57f4a279f6f1ffe8 または Promise \803a2f0672c4eeec57f4a279f6f1ffe8 を返すことができます。これらは、将来のある時点でブール値

1、<span style="font-size: 16px;"></span>CanActivate<span style="font-size: 16px;"></span> に解決されます。 # ユーザーが特定のルートにアクセスできるかどうかを確認します。

CanActivate

はインターフェイスであり、ルート ガード クラスはこのインターフェイスを実装する必要があります。このインターフェイスは、クラスが canActivate メソッドを持つ必要があることを規定しています。ターゲットルートへのアクセスを許可します。 ルートには複数のガードを適用できます。すべてのガード方法が許可されている場合、ルートへのアクセスが許可されます。1 つのガード方法が許可されていない場合、ルートへのアクセスは許可されません。

ルーティング ガードの作成:

ng Guard Guards/auth

<pre class="brush:js;toolbar:false;">&lt;a routerLink=&quot;/user/login&quot;&gt;登录&lt;/a&gt; &lt;a routerLink=&quot;/user/register&quot;&gt;注册&lt;/a&gt;</pre><pre class="brush:js;toolbar:false;">import { Injectable } from &quot;@angular/core&quot; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from &quot;@angular/router&quot; import { Observable } from &quot;rxjs&quot; @Injectable({ providedIn: &quot;root&quot; }) export class AuthGuard implements CanActivate { constructor(private router: Router) {} canActivate(): boolean | UrlTree { // 用于实现跳转 return this.router.createUrlTree([&quot;/user/login&quot;]) // 禁止访问目标路由 return false // 允许访问目标路由 return true } }</pre>

2、<span style="font-size: 16px;"></span>CanActivateChild <span style="font-size: 16px;"></span>#ユーザーが特定のサブルートにアクセスできるかどうかを確認します。

ルーティング ガードの作成:

ng g Guard Guards/admin

注:

CanActivateChild
を選択するには、矢印を次の位置に移動する必要があります。このオプションを選択し、スペースを押して選択を確認します

#

{
  path: "about",
  component: AboutComponent,
  canActivate: [AuthGuard]
}
import { Injectable } from "@angular/core"
import { CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from "@angular/router"
import { Observable } from "rxjs"

@Injectable({
  providedIn: "root"
})
export class AdminGuard implements CanActivateChild {
  canActivateChild(): boolean | UrlTree {
    return true
  }
}
#3,

CanDeactivate<span style="font-size: 16px;"></span><span style="font-size: 16px;">ユーザーがルーティングを終了できるかどうかを確認します。たとえば、ユーザーがフォームに入力した内容が保存されず、ユーザーがルートから離脱したい場合、警備員を呼び出してユーザーに </span>#<pre class="brush:js;toolbar:false;">{ path: &quot;about&quot;, component: AboutComponent, canActivateChild: [AdminGuard], children: [ { path: &quot;introduce&quot;, component: IntroduceComponent } ] }</pre><pre class="brush:js;toolbar:false;">import { Injectable } from &quot;@angular/core&quot; import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from &quot;@angular/router&quot; import { Observable } from &quot;rxjs&quot; export interface CanComponentLeave { canLeave: () =&gt; boolean } @Injectable({ providedIn: &quot;root&quot; }) export class UnsaveGuard implements CanDeactivate&lt;CanComponentLeave&gt; { canDeactivate(component: CanComponentLeave): boolean { if (component.canLeave()) { return true } return false } }</pre><pre class="brush:js;toolbar:false;">{ path: &quot;&quot;, component: HomeComponent, canDeactivate: [UnsaveGuard] }</pre>## と促すことができます。 #4、

#解決

<span style="font-size: 16px;"></span>ルーティングに入る前にデータの取得を許可し、データの取得が完了してからルーティングに入るようにします<span style="font-size: 16px;"><pre class="brush:js;toolbar:false;">import { CanComponentLeave } from &quot;src/app/guards/unsave.guard&quot; export class HomeComponent implements CanComponentLeave { myForm: FormGroup = new FormGroup({ username: new FormControl() }) canLeave(): boolean { if (this.myForm.dirty) { if (window.confirm(&quot;有数据未保存, 确定要离开吗&quot;)) { return true } else { return false } } return true }</pre><pre class="brush:js;toolbar:false;">$ ng g resolver &lt;name&gt;</pre><pre class="brush:js;toolbar:false;">import { Injectable } from &quot;@angular/core&quot; import { Resolve } from &quot;@angular/router&quot; type returnType = Promise&lt;{ name: string }&gt; @Injectable({ providedIn: &quot;root&quot; }) export class ResolveGuard implements Resolve&lt;returnType&gt; { resolve(): returnType { return new Promise(function (resolve) { setTimeout(() =&gt; { resolve({ name: &quot;张三&quot; }) }, 2000) }) } }</pre><pre class="brush:js;toolbar:false;">{ path: &quot;&quot;, component: HomeComponent, resolve: { user: ResolveGuard } }</pre></span>プログラミング関連の知識については、programmingvideo をご覧ください。 !

以上がAngular でのルーティングの詳細と、すぐに始める方法について学びましょう。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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