Following an article on Angular 2 Custom http service here: which also leverages another custom http error service to handle http error codes and reload screen, Code for this service is here:
@Injectable()
export class HttpErrorHandler {
constructor(
private apiGateway: ApiGateway
) {
apiGateway.errors$.subscribe(
(value: any) => {
console.group("HttpErrorHandler");
console.log(value.status, "status code detected.");
console.dir(value);
console.groupEnd();
// If the user made a request that they were not authorized
// to, it's possible that their session has expired. Let's
// refresh the page and let the server-side routing move the
// user to a more appropriate landing page.
if (value.status === 401) {
window.location.reload();
}
});
}
}
What I am trying to achieve is on 401 error redirect to login route using:
router.navigate(['Login']);
However, when I inject Router service in HttpErrorHandler service I get some injection errors.
Error: EXCEPTION: Error during instantiation of Token RouterPrimaryComponent! (Token Application Initializer -> HttpErrorHandler -> Router -> RouteRegistry -> Token RouterPrimaryComponent)
Note: Above HttpErrorHandler is configured during bootstrap phase of application like this:
bootstrap(AppComponent, [
HTTP_PROVIDERS,
ROUTER_PROVIDERS,
ApiGateway,
FriendService,
HttpErrorHandler,
//
// Make sure our "unused" services are created via the
// APP_INITIALIZER token
//
provide(APP_INITIALIZER, {
useFactory: (httpErrorHandler) => {
console.info( "HttpErrorHandler initialized." );
},
deps: [HttpErrorHandler]
})
]);
Not sure if I am injecting Router service quite early in the application lifecycle. Is there any way to inject Router service in HttpErrorHandler service so that client side navigation can be used?
I have created a plnkr here showing the error as well.