Robin Schaaf
Robin Schaaf

Reputation: 145

Angular2 How to display error page while keeping route

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!

Upvotes: 8

Views: 1837

Answers (3)

Tzach Ovadia
Tzach Ovadia

Reputation: 1316

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

Upvotes: 3

Jonas
Jonas

Reputation: 47

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) {

}

Upvotes: -1

Mario Petrovic
Mario Petrovic

Reputation: 8312

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.

Upvotes: 1

Related Questions