在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);
export function destroyView(view: ViewData) { ... if (view.disposables) { for (let i = 0; i < view.disposables.length; i++) { view.disposables[i]();
所以每次你破坏你的指令时,angular会为你处理所有的订阅.