尝试使用已破坏的视图

尝试使用已破坏的视图

本文介绍了ViewDestroyedError:尝试使用已破坏的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(正在使用角度8)

我目前使用行为主题的代码存在问题.

I have an issue currently with my code using a behaviour subject.

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

Component A creates another component B trough the component factory. Now, Component A subscribes to component B it's status to know when to delete it. In this case, whenever there is an error in component B, Component A will change its own status and call Component B.destroy().

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

However, whenever I will run this destory method, I get an error in the logs saying

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

在移除变更检测器之前,我确实先拆开了变更检测器,但这似乎无济于事.

I do untach the change detector before i'm removing it, but that does not seem to help.

这是代码:

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中的两种方法

here are the two methods from component 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.');
  }

推荐答案

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

Oke, somehow i fixed it. It seems due to an unknown issue, the AfterViewInit was called before a certain on change hook. I switched up the code for assinging the behaviour subject and all works well now.

这篇关于ViewDestroyedError:尝试使用已破坏的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:51