在Angular网站上,他们有一个父组件和子组件使用@Output()onVted=new EventEmitter相互交谈的示例
在这个给定的示例中,您是否需要取消订阅EventEmitter以防止内存泄漏/膨胀?或者框架会为您处理这个问题吗?
组件-交互/s rc/app/voter.组件. 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;
}
}
组件-交互/s rc/app/投票者。组件。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
当它销毁yes组件时,它还会自动取消订阅输出订阅:
export function destroyView(view: ViewData) {
...
if (view.disposables) {
for (let i = 0; i < view.disposables.length; i++) {
view.disposables[i]();
因此,每次您销毁您的指令角度将处置所有订阅为您。
但是如果您在代码中手动订阅EventEmitter
,那么您必须自己取消订阅。
我认为您不必取消订阅。由于您没有使用子到父组件迭代从API获取数据,因此没有必要取消订阅。