Angular 2で前のページに戻る:location、Router、@CanActivateガード、history.back()
Angular 2 で前のページに戻る方法
location.back() を使用する
これは、前のページに戻る最も簡単な方法です。 location
オブジェクトの back()
メソッドを呼び出すだけです。
import { Location } from '@angular/common';
constructor(private location: Location) {}
goBack() {
this.location.back();
}
Router を使用する
Router
サービスを使用すると、プログラムで特定のページに移動できます。 前のページに戻るには、navigateBack()
メソッドを使用します。
import { Router } from '@angular/router';
constructor(private router: Router) {}
goBack() {
this.router.navigateBack();
}
@CanActivate
ガードを使用して、ユーザーが特定のページにアクセスできるかどうかを制御できます。 前のページに戻る必要がある場合は、CanActivate
ガード内で false
を返すことができます。
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class CanActivateGuard implements CanActivate {
constructor(private router: Router) {}
canActivate() {
if (this.canGoBack()) {
return true;
} else {
this.router.navigate(['/']);
return false;
}
}
private canGoBack() {
return this.router.url !== '/';
}
}
これは、JavaScript のネイティブ API を使用する最も単純な方法です。 ただし、この方法は Angular 2 に依存していないため、すべての状況で動作するとは限りません。
history.back();
補足
上記の方法は、すべて前のページに戻るための有効な手段です。 どの方法を使用するかは、具体的な状況によって異なります。
- location.back() は、最も簡単な方法ですが、プログラムで制御できないという欠点があります。
- Router は、プログラムで制御できるという利点がありますが、コード量が増えるという欠点があります。
- @CanActivate ガード は、特定の条件下でのみ前のページに戻る必要がある場合に便利です。
- history.back() は、最も単純な方法ですが、すべての状況で動作するとは限りません。
app.component.html
<h1>Home</h1>
<button (click)="goBack()">前のページに戻る</button>
<router-outlet></router-outlet>
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private location: Location, private router: Router) {}
ngOnInit() {}
goBack() {
// location.back() を使用する
this.location.back();
// Router を使用する
// this.router.navigateBack();
// history.back() を使用する
// history.back();
}
}
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { OtherComponent } from './other.component';
const routes: Routes = [
{ path: '', component: AppComponent },
{ path: 'other', component: OtherComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<h1>Other Page</h1>
<button (click)="goBack()">Homeに戻る</button>
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
@Component({
selector: 'my-other',
templateUrl: './other.component.html',
styleUrls: ['./other.component.css']
})
export class OtherComponent implements OnInit {
constructor(private location: Location, private router: Router) {}
ngOnInit() {}
goBack() {
// location.back() を使用する
this.location.back();
// Router を使用する
// this.router.navigateBack();
// history.back() を使用する
// history.back();
}
}
このサンプルコードを実行すると、以下の動作を確認できます。
- Home ページで "前のページに戻る" ボタンをクリックすると、ブラウザの戻るボタンと同じように前のページに戻ります。
- Other ページで "Homeに戻る" ボタンをクリックすると、Home ページに戻ります。
Angular 2 で前のページに戻る方法はいくつかあります。 どの方法を使用するかは、具体的な状況によって異なります。 上記のサンプルコードを参考に、自分に合った方法を選択してください。
Angular 2 で前のページに戻るその他の方法
@HostListener
デコレータを使用して、ブラウザの戻るボタン押下イベントをリッスンできます。
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[goBack]'
})
export class GoBackDirective {
constructor() {}
@HostListener('window:popstate')
onPopState() {
// 前のページに戻る処理
}
}
Subject
を使用して、コンポーネント間でイベントを伝達できます。
import { Subject } from 'rxjs';
export class MyService {
private backSubject = new Subject();
constructor() {}
goBack() {
this.backSubject.next();
}
get back() {
return this.backSubject.asObservable();
}
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private myService: MyService) {}
ngOnInit() {
this.myService.back.subscribe(() => {
// 前のページに戻る処理
});
}
}
URL パラメータを使用して、前のページに戻るための情報を保存できます。
import { Router } from '@angular/router';
constructor(private router: Router) {}
goBack() {
this.router.navigate(['/previous', { page: 'home' }]);
}
上記の方法以外にも、さまざまな方法で前のページに戻ることは可能です。 具体的な状況に合わせて、最適な方法を選択してください。
Angular 2 で前のページに戻る方法はたくさんあります。 上記で紹介した方法を参考に、自分に合った方法を選択してください。
angular angular2-routing