【问题标题】:Does a ComponentRef.destroy() method also unsubscribe the Components Event Emitters?ComponentRef.destroy() 方法是否也取消订阅组件事件发射器?
【发布时间】:2019-01-11 04:34:54
【问题描述】:

如果我们有一个动态(动态创建 - 非声明式)ComponentRef 实例,并且我们在该实例上调用 destroy(),这是否会取消订阅已订阅的 EventEmitter 实例。

例如,如果我们是 output EventEmitter 并且我们像这样订阅它:

this.componentRef.instance.output.subscribe(event => console.log(event));

我们打电话给componentRef.destroy() 会负责取消订阅outputEventEmitter吗?

包含答案的摘要文章

https://medium.com/@ole.ersoy/subscribing-to-dynamic-component-eventemitters-4f931a5013e3

https://medium.com/@ole.ersoy/cleaning-up-subscriptions-to-dynamic-component-event-emitters-ad08c838c7a8

【问题讨论】:

    标签: javascript angular typescript rxjs


    【解决方案1】:

    当调用 subscribe 方法时,会返回一个订阅对象。如果我跟踪那个对象。每当 Angular 销毁组件时,您都必须调用 unsubscribe。

    E.x:

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

    不会取消订阅ngOnDestroy()

    【讨论】:

      【解决方案2】:

      有一个来自 componentRef 的 onDestroy 回调,您可以挂钩以清理订阅

        /**
         * A lifecycle hook that provides additional developer-defined cleanup
         * functionality for the component.
         * @param callback A handler function that cleans up developer-defined data
         * associated with this component. Called when the `destroy()` method is invoked.
         */
        abstract onDestroy(callback: Function): void;
      

      例子

      const sub=this.componentRef.instance.output.subscribe(event => console.log(event));
      this.componentRef.onDestroy(()=>{
          sub.unsubscribe()
      })
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多