Alb*_*ert 4 error-handling ngoninit angular
Angular 4应用程序.
我正在尝试创建一个错误页面,以显示有关可能发生的未处理异常的一些信息.该GlobalErrorHandler拦截最终的错误和用户由单一的页面重定向ErrorComponent.发生错误时会显示页面,但不会调用生命周期挂钩.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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");
}
}
Run Code Online (Sandbox Code Playgroud)
关于plunkr的工作演示.
我怎么解决这个问题?也许有人知道解决方法?谢谢
找到这个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']));
}
}
}
Run Code Online (Sandbox Code Playgroud)