代码之家  ›  专栏  ›  技术社区  ›  Igneous01

角度7-导航和OnDestroy定时问题

  •  0
  • Igneous01  · 技术社区  · 6 年前

    我们刚刚将我们的项目从Angular6升级到Angular7,并注意到以下问题,即在组件被破坏之前,NavigationEnd事件被发出。在升级到Angular7之前,我们看到NavigationEnd事件在组件被破坏后发出。

    widgetcontainercomponent的每个实例订阅一个在ngoninit中可见的配置,ngondestory将取消订阅它。

      constructor(@SkipSelf() private dataProviderDirective: DataProviderDirective) {
        super();
      }
    
      ngOnInit(): void {
        console.log("WidgetContainer.ngOnInit called");
        const _self = this;
        this.dataProviderDirective.getConfigurationPublisher().subscribe(widgetConfigurations => {
          _self.processConfiguration(widgetConfigurations, this.alias);
          this.subscribe(this.wsDataTopic + this.configuration.id, (message: Message) => this.onDataTopic(message));
          this.subscribe(this.wsStaleTopic + this.configuration.id, (message: Message) => this.onStaleTopic(message));
        });
      }
    
      ngOnDestroy(): void {
        console.log("WidgetContainer.ngOnDestroy() called");
      }
    

    包含这些组件的另一个组件(DashboardContainerComponent)具有以下功能:

      navigationSubscription;
    
      constructor(@Host() private dashboardComponent: DashboardComponent, private router:Router) {
        super();
        this.navigationSubscription = this.router.events.subscribe((e: any) => {
          // If it is a NavigationEnd event re-initalise the component
          if (e instanceof NavigationEnd) {
            console.log("DashboardContainerComponent.onNavigationEnd()");
            this.initialize();
          }
        });
      }
    
      ngAfterViewInit(): void {
        console.log("DashboardContainerComponent.ngAfterViewInit()");
        this.initialize();
      }
    
      ngOnDestroy(): void {
        if (this.navigationSubscription) {
          this.navigationSubscription.unsubscribe();
        }
      }
    
      private initialize(): void {
        this.publishConfiguration(this.dashboardComponent.getWidgets());
      }
    

    我们期望看到的是,当从一个仪表板页面导航到另一个仪表板时,屏幕上现有的WITGeCuultEngices组件将首先被销毁,然后触发导航结束事件,导致容器从服务器重新加载新的小部件配置。同时,正在为新仪表板页面重新创建新的WidgetContainerComponents,并订阅Containers配置事件。

    然而,我们看到的是,用户导航到一个新的仪表板,导航端被发出,容器发出新的小部件配置。然后,旧的容器容器实例+新的容器都试图处理这个事件,而旧的小部件容器出错,因为它们寻找的数据不存在(因为它们不是这个页面的一部分)。

    我们不确定这是否是有意改变这些生命周期事件发生的时间,但我们能做些什么来防止这种情况发生吗?

    0 回复  |  直到 6 年前