【问题标题】:Does an angular component ever destroy when it is subscribed to router change event once?订阅路由器更改事件一次时,角度组件是否会破坏?
【发布时间】:2019-11-13 03:26:35
【问题描述】:

在一个特定的路由中,我正在加载一个订阅 router.events 的组件,以检测该组件中的任何路由更改(如 queryparams)。当我转到加载不同组件的不同路由时,即使在加载新组件之前在第一个组件上调用了 ngOnDestroy 生命周期挂钩,仍然会调用第一个组件的 router.event。我的问题是调用 ngOnDestroy 这意味着第一个组件应该销毁。那么为什么在每次路由更改时仍然调用订阅的 router.events 。

 this.router.events.subscribe((event: any) => {
        if (event instanceof NavigationEnd) {
            this.applicationItemIdChange = this.route.snapshot.params['id'];
            if (this.applicationItemId && this.applicationItemIdChange && this.applicationItemIdChange !== this.applicationItemId) {
                this.ngOnInit();
            }

        }
    });

【问题讨论】:

    标签: angular


    【解决方案1】:

    那是因为您的程序中存在内存泄漏。 subscriptionthis.router.events 几乎是一个永无止境的订阅。所以一旦你卸载了你的组件,你应该明确地unsubscribe

    this.subscription = this.router.events.subscribe((event: any) => {
      if (event instanceof NavigationEnd) {
        this.applicationItemIdChange = this.route.snapshot.params['id'];
        if (this.applicationItemId && this.applicationItemIdChange && this.applicationItemIdChange !== this.applicationItemId) {
          this.ngOnInit();
        }
      }
    });
    

    在这里,我们将Subscription 存储在一个属性中。

    然后在ngOnDestroy:

    ngOnDestroy() {
      this.subscription.unsubscribe();
    }
    

    我们从Subscription手动unsubscribe

    【讨论】:

      【解决方案2】:

      原因是,尽管您的组件已被销毁,但您仍在订阅事件。

      所以要么你需要保持对subscriptions 和unsubscribe 的引用(作为@siddAjmera 的答案)

      或者您可以使用此模式取消订阅多个订阅,而无需定义多个变量。

      class mycomp implements OnDestroy {
      
        private unsubscribeAll : Subject<Any> = new Subject<any>();
      
        ngOnDestroy() {
           this.unsubscribeAll.next();
           this.unsubscribeAll.complete();
        }
      
        foo() {
           this.router.events
           .pipe(
              takeUntil(this.unsubscribeAll)
           )
           .subscribe(...)    
      
      
           observable1
           .pipe(
              takeUntil(this.unsubscribeAll)
           )
           .subscribe(...)
      
        }
      
        bar() {
           observable2
           .pipe(
              takeUntil(this.unsubscribeAll)
           )
           .subscribe(...)
        }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2017-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-06
        • 1970-01-01
        • 2017-03-25
        • 2019-06-15
        • 1970-01-01
        相关资源
        最近更新 更多