ngOnInit does not run on error page component

1.5k views Asked by At

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

1

There are 1 answers

2
n00dl3 On

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 :

@Injectable()
export class GlobalErrorHandler extends ErrorHandler {

    constructor(private injector: Injector private zone: NgZone) {
        super();
    }

    handleError(error: any) {
        const router = this.injector.get(Router);
        super.handleError(error);
        if (!router.url.startsWith('/error')) {
            this.zone.run(()=>router.navigate(['/error']));
        }
    }

}