【Angular】実装メモ~Router編~

Routing

 

実装

 

画面遷移の設定

  • app-routing.module.ts内に定義する

 

初期画面の設定

  • パス指定無しの場合のリダイレクト設定

  • pathMatch: 'full'はパスの完全一致

{ path: '', redirectTo: 'top', pathMatch: 'full' },

 

ルートの設定

{ path: 'top', component: TopComponent },

 

子ルートの設定

  • パスは「/${親path}/${子path}」

    • 例の場合は/top/child

{ 
 path: 'top',
 component: TopComponent,
 children: [
  {
     path: 'child',
     component: ChildComponent,
  },
]
},

 

パスに一致するものが無い場合の設定

{ path: '**', component: TopComponent }

 

 

画面遷移処理の実装

 

HTMLに実装

  • /を外すと子ルートへのパスになる

<a routerLink="/top">画面遷移</a>

 

Componentに実装

import { Component, OnInit } from '@angular/core';
// インポートを追加
import { Router } from '@angular/router';

@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss'],
})
export class TestComponent implements OnInit {
 // RouterをInjection
 constructor(private router: Router) {}

 ngOnInit(): void {}

 onClickButton(){
   // 画面遷移
   this.router.navigate(['/top']);
}
}

 

 

Guard

Guradの種類

NO 種類 概要 ユースケース
1 canActivate ・画面遷移時に実行される ・戻り値がfalseの場合は画面遷移しない ・画面遷移時の認証状態チェック
2 canActivateChild ・処理タイミングはcanActivateと同じ ・子ルートの制御に使用する ・権限ごとの表示項目制御
3 canDeactivate ・画面から離れる時に実行される ・画面から離れる時の確認
4 canLoad ・モジュールを読み込み時に実行される ・権限ごとの遅延ロード可否
5 resolve ・画面遷移前に実行される ・データ取得を行い遷移先に渡す ・外部APIへのアクセス等でデータ取得に時間がかかる場合に使用する ・canActivate等とは違い処理時間がかかっても空白画面が表示されない ※serviceとして作成する ・外部APIからデータが取得できた場合だけ特定画面に遷移

 

生成コマンド

  • Angular-CLIのコマンド

  • 実装するGuardを選択する

ng g guard ${ガード名}

 

Guardの実装

例)canActivate

  • 画面遷移時に認証状態を確認する

import { Injectable } from '@angular/core';
import {
 CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router,} from '@angular/router';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { AppStore, Storekey } from 'src/app/state/store/store-definition';
import { tap } from 'rxjs/operators';

@Injectable({
 providedIn: 'root',
})
export class AuthGuard implements CanActivate {
 /** 認証状態 */
 isloggedIn$: Observable<boolean>;

 constructor(private store: Store<AppStore>, private router: Router) {
   this.isloggedIn$ = store.select(Storekey.isloggedIn);
}

 canActivate(
   next: ActivatedRouteSnapshot,
   state: RouterStateSnapshot
):
   | Observable<boolean | UrlTree>
   | Promise<boolean | UrlTree>
   | boolean
   | UrlTree {
   return this.isloggedIn$.pipe(
     tap((loggedIn) => {
       // 認証されていない場合に特定画面に遷移
       if (!loggedIn) {
         this.router.navigate(['/login']);
      }
    })
  );
}
}

 

ルートに設定

{ path: 'top', component: TopComponent, canActivate: [AuthGuard] }