28

How Can I redirect to another page if the resolve fails in Angular 2? I call this resolve for my Edit Page, but I want to handle the errors in the Resolve Page

My Resolve:

 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);
            });
    }});
1

2 Answers 2

40

Just like in the docs, calling this.router.navigate(["url"])... (think to inject Router in your constructor)

class MyResolve {

  constructor(private router: Router) {}

  resolve(route: ActivatedRouteSnapshot): Observable <any> {
    return this.dataService.getHttpEmpresaShow(this.endpoint_url_Get + route.params['id'])
      .pipe(catchError(err => {
        this.router.navigate(["/404"]);
        return EMPTY;
      }));
  }
}
Sign up to request clarification or add additional context in comments.

13 Comments

It's really not convenient to have a /404 route! Ideally, we should be able to keep the original url (e.g. posts/some-missing-id) and show an error component instead of original handler component. Is there any way to implement such mechanism to (globally) handle errors in resolve guards?
It's really convenient to have a 404 route ! Instead of having spaghetti code with ngIf="error" it is centralized. If you want to keep the url take a look at the router documentation and NavigationExtras
This is a bad practise. I've never seen a backend web server ever redirect to a dedicated 404 webpage. So why do this on the frontend?
I think you don&#39;t understand what is done here. If you have a router outlet that is made to display a single item, and when you don&#39;t find the item, you display a 404 message in the same place without changing the url. That&#39;s the exact behavior you talked about ! You just need to pass {skipLocationChang:true} as an option to router.navigate(url, options). @cgTag
@n00dl3, did you try it yourself? skipLocationChang:true is not working in case of data resolver I dunno why. If the URL which you visit is first URL and resolved can't resolve data and redirects to 404, original URL not saved and always become just "/" root URL without path, this.router.navigate(['404'], {skipLocationChange: true}); doesn't help. Angular 4. Not sure if that's a bug of router or it's a feature...
|
1

Another solution, if you want to apply a redirect strategy after failling for ALL of your resolvers, you can intercept a router event and apply redirect on a fail event. Here the code you can add in your AppComponent :

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { Router, RouterEvent, NavigationError } from '@angular/router';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor(
    private router: Router,
    private cdr: ChangeDetectorRef
  ){}


  ngOnInit() {    
    this.router.events.subscribe((event: RouterEvent) => {
      this.navigationInterceptor(event)
    });
  }

  navigationInterceptor(event: RouterEvent): void {
    if (event instanceof NavigationError) {
      this.router.navigate(["error"],{ queryParams: { redirect: event.url } });
    }
    this.cdr.detectChanges();
  }

}

1 Comment

The problem with this is that if you have nested component routes that you want to direct to, you need to now the entire path to the result, where as a redirectTo in place takes the route you want, and is defined at the path level

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.