I have 50 http api's in my application. I want to route to a page when error message or error occurs in an api i don't want to go to all service and add routing there i want to do it dynamically and simple? Any idea?
CodePudding user response:
Yes, you can use Http Interceptor to implement that.
Http Interceptor is standing between the client-side and the server-side and it catches every request and every response between.
So, you can catch the HTTP Response errors and navigate the user, something like:
@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
constructor(private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any> | any> {
return next.handle(req).pipe(
tap(event => {
// catch the success response
}, err => {
// navigate in case of errors
this.router.navigate(['/error-page'])
})
);
}
}