Redirect if Resolve fails Angular 2
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();
}
}
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;
}));
}
}