Angular2 How to display error page while keeping route

你说的曾经没有我的故事 提交于 2019-12-05 23:23:22

问题


Apologies if this is somewhere else, but my normal searching tactics have failed me.

I'd like to display a custom error page when I receive a 500 from the API. I'm using restangular and have a response interceptor that redirects to the error page when I receive the 500, using:

this.router.navigate(['/error']);

This all works. However, I'd like to keep the previous URL in the browser navigation bar so that when the user refreshes it tries the previous page again, whereas right now they have to re-navigate to the broken page to try again.

Thanks!


回答1:


You can add this:

setRouteErrorHandler(): void {
    let errorRoute = null;

    this.router.errorHandler = (error): void => {
        this.location.go(errorRoute.url);
        this.router.navigate(['/error'], { skipLocationChange: true, replaceUrl: true });
    };

    this.router.events
        .filter((next) => next instanceOf NavigationError)
        .subscribe((next) => {
            errorRoute = next;
    });
}

and call setRouteErrorHandler() from AppModule constructor or implement your own APP_INITIALIZER




回答2:


There is no direct way to do that. But you can redirect to error page and either save previous page in localStorage or put it i request param /error?page=redirectUrl.

Than when you refresh you navigate to that page again using that param value or localStorage data.




回答3:


I should have made an ErrorComponent wich renders upon errors, just swap the components upon success or error.

This is ofcourse a shared component with a

try {

}
catch (e) {

}


来源:https://stackoverflow.com/questions/44075354/angular2-how-to-display-error-page-while-keeping-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!