Angular 2 でリダイレクトを使いこなす!RouterとrouterLink徹底比較
Angular 2 コンポーネント内でのリダイレクト
Router を利用する
- Router サービスをインジェクションする
import { Router } from '@angular/router';
constructor(private router: Router) {}
- router.navigateByUrl() または router.navigate() を使用する
this.router.navigateByUrl('/target-component'); // 絶対パスで指定
this.router.navigate(['./relative-component']); // 相対パスで指定
routerLink ディレクティブを使用する
- HTML テンプレートに routerLink ディレクティブを追加
<a [routerLink]="'/target-component'">ターゲットコンポーネントへ移動</a>
補足
- 上記以外にも、
ActivatedRoute
サービスやCanActivate
ガードを利用したリダイレクト方法もあります。
Angular 2 コンポーネント内リダイレクト サンプルコード
app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private router: Router) {}
redirectToTarget() {
this.router.navigateByUrl('/target-component');
}
}
<button (click)="redirectToTarget()">ターゲットコンポーネントへリダイレクト</button>
<a routerLink="/target-component">ターゲットコンポーネントへ移動</a>
- 上記はあくまでも基本的な例です。実際のアプリケーションでは、状況に応じて様々なリダイレクト方法を使い分けることができます。
- リダイレクトを行う前に、必要なデータを次のコンポーネントに渡す必要がある場合は、
queryParams
やstate
プロパティを利用することができます。 - セキュリティ上の理由から、ユーザーが意図しないリダイレクトを防止する対策も必要です。
Angular 2 コンポーネント内リダイレクト:その他の方法
window.location オブジェクトを使用する
window.location.href
プロパティに新しいURLを代入することで、ブラウザを直接新しいページに遷移させることができます。
window.location.href = '/target-component';
Location サービスを使用する
Location
サービスは、ブラウザの履歴と現在のURLを操作するための機能を提供します。go()
メソッドを使用して、指定された履歴エントリへ移動することができます。
import { Location } from '@angular/common';
constructor(private location: Location) {}
redirectToTarget() {
this.location.go('/target-component');
}
ngZone
サービスは、Angular アプリケーション内の非Angular コードを実行するための安全な方法を提供します。run()
メソッドを使用して、非Angular コードを実行することができます。
import { NgZone } from '@angular/core';
constructor(private ngZone: NgZone) {}
redirectToTarget() {
this.ngZone.run(() => {
window.location.href = '/target-component';
});
}
- 上記の方法はいずれも、
Router
サービスやrouterLink
ディレクティブよりも低レベルな方法です。 - 上記の方法を使用する場合は、以下の点に注意する必要があります。
- ブラウザの履歴が更新されない可能性がある
- コンポーネント間のデータ共有が困難になる
- ユニバーサルアプリケーションでは動作しない可能性がある
javascript angular