2017-03-01 1 views
2

私のアプリケーションのPageNotFoundコンポーネントを作成し、ここにリンクを追加します。 "Go Back"ですが、履歴が空であればメインページ "/"にリダイレクトします。location.back()outside applicationを避ける2

import { Component, OnInit } from '@angular/core'; 
import { Title } from '@angular/platform-browser'; 
import { Location } from '@angular/common'; 

@Component({ 
    selector: 'page-not-found', 
    templateUrl: './app/error/page-not-found/page-not-found.component.html' 
}) 
export class PageNotFoundComponent implements OnInit { 
    constructor(private titleService: Title, 
     private location: Location) { } 

    ngOnInit() { 
     this.titleService.setTitle('Page Not Found'); 
    } 

    back() { 
     //check if history is empty somehow and execute 'this.router.navigate["/"];' 
     this.location.back(); 
    } 
} 

どうすれば実装できますか?

+0

http://stackoverflow.com/questions/18784814/browser-back-event-without-onbeforeunload-and-unload-events –

+0

まず、あなたはあなたのアプリの外に何もコントロールできません。そして、あなたは 'location.back'の代わりに' router.navigate'を使うことができます。つまり、これはすべてurアプリケーション内にとどまります。 – Smit

+0

'router.navigate'の使用をどうお勧めしますか?常にメインページにリダイレクトしますか? –

答えて

1

私は、次の方法でそれを解決:すべての

back() { 
     if (window.history.length > 1) { 
      this.location.back(); 
     } else { 
      this.router.navigate(['/']); 
     } 
    } 
関連する問題