angular – 您是否需要取消订阅@Output EventEmitter

前端之家收集整理的这篇文章主要介绍了angular – 您是否需要取消订阅@Output EventEmitter前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Angular网站上,他们有一个父和子组件的例子,它们使用@Output()onVoted = new EventEmitter< boolean>();相互交谈.见下文.

在这个给定的示例中,您是否需要取消订阅EventEmitter以防止内存泄漏/膨胀?或者框架是否为您解决了这个问题?

组件的相互作用/ SRC /应用程序/ voter.component.ts

import { Component,EventEmitter,Input,Output } from '@angular/core';

@Component({
  selector: 'app-voter',template: `
    <h4>{{name}}</h4>
    <button (click)="vote(true)"  [disabled]="voted">Agree</button>
    <button (click)="vote(false)" [disabled]="voted">Disagree</button>
  `
})
export class VoterComponent {
  @Input()  name: string;
  @Output() onVoted = new EventEmitter<boolean>();
  voted = false;

  vote(agreed: boolean) {
    this.onVoted.emit(agreed);
    this.voted = true;
  }
}

组件的相互作用/ SRC /应用程序/ votetaker.component.ts

import { Component }      from '@angular/core';

@Component({
  selector: 'app-vote-taker',template: `
    <h2>Should mankind colonize the Universe?</h2>
    <h3>Agree: {{agreed}},Disagree: {{disagreed}}</h3>
    <app-voter *ngFor="let voter of voters"
      [name]="voter"
      (onVoted)="onVoted($event)">
    </app-voter>
  `
})
export class VoteTakerComponent {
  agreed = 0;
  disagreed = 0;
  voters = ['Mr. IQ','Ms. Universe','Bombasto'];

  onVoted(agreed: boolean) {
    agreed ? this.agreed++ : this.disagreed++;
  }
}

解决方法

如果您在Angular网站上看到示例并且他们没有取消订阅那么您认为为什么要这样做呢?

Angular关心它.

当它创建指令实例时,它订阅输出

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

当它破坏组件时,它还会自动取消订阅输出订阅

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

所以每次你破坏你的指令时,angular会为你处理所有的订阅.

但是如果您在代码中手动订阅EventEmitter,那么您必须取消订阅.

猜你在找的Angularjs相关文章