Do you need to unsubscribe from @Output EventEmitter

后端 未结 2 999
自闭症患者
自闭症患者 2021-01-04 04:07

On the Angular website they have an example of a Parent and Child component talking to each other using @Output() onVoted = new EventEmitter();.

相关标签:
2条回答
  • 2021-01-04 04:35

    If you see example on the Angular website and they don't unsubscribe then why do you think you should do it?

    Angular takes care about it.

    When it creates directive instance it subscribes to the outputs:

    if (def.outputs.length) {
        for (let i = 0; i < def.outputs.length; i++) {
          const output = def.outputs[i];
          const subscription = instance[output.propName !].subscribe(
              eventHandlerClosure(view, def.parent !.nodeIndex, output.eventName));
          view.disposables ![def.outputIndex + i] = subscription.unsubscribe.bind(subscription);
    

    https://github.com/angular/angular/blob/235a235fab45b2c82f8758fc9c0779f62a5b6c04/packages/core/src/view/provider.ts#L138-L140

    and when it destroyes component it also automatically unsubscribes from output subscriptions:

    export function destroyView(view: ViewData) {
      ...
      if (view.disposables) {
        for (let i = 0; i < view.disposables.length; i++) {
          view.disposables[i]();
    

    So every time you destroy your directive angular will dispose all subscription for you.

    But if you subscribe to EventEmitter manually in code then you have to unsubscribe yourself.

    0 讨论(0)
  • 2021-01-04 04:48

    i think you don't have to do unsubscribe. Since You are not using child to parent component iteration for fetching data from API there is no need to unsubscribe.

    0 讨论(0)
提交回复
热议问题