NgOnInit not working on error page component

Angular 4.

I am trying to make an error page to show some information about an unhandled exception that might occur. GlobalErrorHandlerintercepts possible errors and redirects the user to a page consisting of one ErrorComponent. When an error occurs, the page is displayed, but lifecycle hooks are not 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 can i fix this? Maybe someone knows a workaround? Thanks

+4
source share
1 answer

github. , router.navigate(...) angular, :

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']));
        }
    }

}
+4

Source: https://habr.com/ru/post/1685880/


All Articles