请考虑以下代码:
//our root app component
import {ChangeDetectionStrategy, Component, ErrorHandler, Injector, NgModule, ViewContainerRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {ToastModule, ToastsManager} from "ng2-toastr/ng2-toastr";
@Component({
selector: 'my-app',
template: `
<div>
name={{(test$|async).name}}
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class App {
test$: Observable<{name:string}> = null;
constructor(toastr: ToastsManager, viewContainerRef: ViewContainerRef) {
toastr.setRootViewContainerRef(viewContainerRef);
}
}
export class CustomErrorHandler extends ErrorHandler {
constructor(private injector: Injector) { super(); }
handleError(err: any): void {
super.handleError(err);
this.injector.get(ToastsManager).error(err.message);
}
}
@NgModule({
imports: [ BrowserModule, BrowserAnimationsModule, ToastModule.forRoot() ],
declarations: [ App ],
bootstrap: [ App ],
providers: [
{ provide: ErrorHandler, useClass: CustomErrorHandler, deps: [Injector] }
]
})
export class AppModule {}
也可用作Plunker here .
在组件模板中故意触发错误(
test
未定义)。自定义错误处理程序启动,记录错误并尝试弹出错误消息。不仅不会弹出 toast,而且应用程序还会一遍遍地记录原始错误。挖一点似乎表明这是由重复调用 toastr 的 setTimeout 函数引起的。我试过用不同的 toastr 库做类似的事情,但结果相同。预期的行为是 toast 弹出一次并且错误只记录一次。
关于如何实现这一目标的任何想法?
最佳答案
抛出handleError()
结尾的错误.
来源:https://github.com/scttcper/ngx-toastr/issues/564#issuecomment-419910273
This isn't an issue with ngx-toastr.
What is happening is that if there's something like a template error and you've "handled" the error, change detection will continue to run over and over causing the infinite loop. You need to throw an error at the end of the function.
However, since unhandled http errors (and other smaller errors that could be easily handled) will also throw the error at the end and will cause change detection to stop running. The trick is to only throw an error at the end when it's something that you cannot handle or that should cause change detection to stop running (like template errors)
关于Angular - 模板中的错误导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48694217/