ViewDestroyedError:尝试使用已破坏的视图

时间:2019-06-07 18:06:35

标签: angular components observable destroy behaviorsubject

(正在使用角度8)

我当前使用行为主题的代码存在问题。

组件A通过组件工厂创建另一个组件B。现在,组件A订阅了组件B的状态,以知道何时删除它。在这种情况下,只要组件B中出现错误,组件A就会更改其自身的状态并调用组件B.destroy()。

但是,每当我运行此销毁方法时,都会在日志中显示一条错误消息

ERROR Error: ViewDestroyedError: Attempt to use a destroyed view: detectChanges

在删除变更检测器之前,我确实先解开了它,但这似乎无济于事。

这是代码:

createComponent(): void {
    this.logger.debug('Widget: creating component based on type provided in config.');

    this.setWidgetLoading(true);
    this.componentFactory.createComponent(this.content, this.componentConfig).subscribe((componentRef) => {

        this.componentRef = componentRef;

        this.componentRef.instance.componentStatus.subscribe((status: Status) => {
          this.setComponentStatus(status);
        });

      }, (error: Error) => {
        this.setComponentStatus(StatusFactory.createErrorStatus(error));
        this.setWidgetLoading(false);
      },
      () => {
        this.setWidgetLoading(false);
        this.logger.debug('Widget: component created based on type provided in config.');
      });

  }

setComponentStatus(status: Status): void {

 case STATUS_TYPE.ERROR:
        this.setWidgetLoading(false);
        this.componentRef.changeDetectorRef.detach();
        this.componentRef.destroy(); //componentRef references the created component B
        return;
}

编辑

这是组件B中的两种方法

 ngAfterViewChecked(): void {
    if (this.config.mode === ENTITY_FORM_MODE.UPDATE && !this.data) {
      this.logger.debug('EntityCreationComponent: initialized for update mode but no data provided.');
      this.setErrorStatus(ErrorFactory.createError('initialized for update mode but no data provided.'));
    }
  }

  ngOnInit() {
    super.ngOnInit();
    this.entity = Object.assign(this.entity ? this.entity : {}, EntityFactory.createEntity(this.config.dataConfig.dataType));

    this.logger.debug('EntityCreationComponent: initialized.');
  }

1 个答案:

答案 0 :(得分:0)

好吧,我以某种方式解决了它。似乎是由于一个未知的问题,AfterViewInit在某个变更挂钩之前被调用。我切换了代码来查询行为主题,现在一切正常。