Angular 4 application.
I am trying to make an error page in order to show some information about the unhandled exception that may occur. The GlobalErrorHandler
intercepts eventual errors and redirects the user to a page consisting of a single ErrorComponent
. When the error occurs the page is shown, but life cycle hooks do not get called.
ErrorHandler :
@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
constructor(
private injector: Injector
) {
// The true paramter tells Angular to rethrow exceptions, so operations like 'bootstrap' will result in an error
// when an error happens. If we do not rethrow, bootstrap will always succeed.
super(true);
}
handleError(error: any) {
const router = this.injector.get(Router);
if (!router.url.startsWith('/error')) {
router.navigate(['/error']);
}
super.handleError(error);
}
}
ErrorComponent :
@Component({
selector: 'error-desc',
template: '<h1>Error page = {{code}}</h1>'
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ErrorComponent implements OnInit {
public code: string = '';
constructor(
) {}
ngOnInit() {
// not called
this.code="AAAA";
console.log("OnInit");
}
ngOnDestroy() {
console.log("OnDestroy");
}
}
Working demo on plunkr.
How I can fix this? Maybe someone knows workaround? Thanks
After finding this github issue. It seems you just have to run your
router.navigate(...)
code inside angular's zone to get the redirection up and running :ErrorHandler :