ViewDestroyedError: Attempt to use a destroyed view

折月煮酒 提交于 2019-12-11 23:09:57

问题


(angular 8 in use)

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

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.

Here is the code:

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;
}

EDIT

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.');
  }

回答1:


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.



来源:https://stackoverflow.com/questions/56499302/viewdestroyederror-attempt-to-use-a-destroyed-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!