2017-03-29 94 views
8

如何在Angular 2中解決失敗時如何重定向到另一頁? 我把這種決心爲我的編輯頁面,但我想以處理解決頁面錯誤解決失敗時重定向Angular 2

我的決心:

resolve(route: ActivatedRouteSnapshot): Promise<any>|boolean { 

     return new Promise((resolve, reject) => { 

      if (route.params['id'] !== undefined) { 
       this.dataService.getHttpEmpresaShow(this.endpoint_url_Get + route.params['id']) 
        .subscribe(
        result => {      
          console.log("ok"); 
          return resolve(result);      
        }, 
        error => { 
       return resolve(error); 
      }); 
    }}); 

回答

15

就像in the docs,調用this.router.navigate(["url"]) ......(想注入Router在你的構造函數)

class MyResolve { 

    constructor(private router: Router) {} 

    resolve(route: ActivatedRouteSnapshot): Observable <any> { 
    return this.dataService.getHttpEmpresaShow(this.endpoint_url_Get + route.params['id']) 
     .catch(err => { 
     this.router.navigate(["/404"]); 
     return Observable.empty(); 
     }); 
    } 
} 
+0

它的工作!..... –

+3

有一個**/404 **路線真的不方便!理想情況下,我們應該能夠保留原始URL(例如posts/some-missing-id)並顯示錯誤組件而不是原始處理程序組件。有沒有什麼方法可以實現這種機制(全局)處理解決方案中的錯誤? –

+0

擁有404路線真的很方便! 'ngIf =「error」的意大利麪代碼不是集中式的。如果你想讓網址看一下[router documentation](https://angular.io/api/router/Router)和[NavigationExtras](https://angular.io/api/router/NavigationExtras) – n00dl3