Angular - 模板中的错误导致无限循环

标签 angular

请考虑以下代码:

//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/

相关文章:

angular - 测试广播服务

javascript - 响应式(Reactive)表单验证不起作用

angular - ngSubmit.emit() 不会改变 formGroup 的提交属性

Angular 5 - HTTP Post x-www-form-urlencoded

angularjs - Angular 的可观察响应中不存在属性图

javascript - ngx-editor 链接重定向到与 Angular 项目 url 相结合的 url

angular - 如果以 Angular 调用两次,如何等待相同的可观察对象完成?

javascript - Angular Universal,在单击 'refresh' 两次之前应用程序不会加载

javascript - 如何在 Angular 中将非哈希 URL 重定向到具有哈希的 URL?

javascript - 由于变量尚未加载,无法绑定(bind)到子组件的属性?