您是否需要退订@Output EventEmitter [英] Do you need to unsubscribe from @Output EventEmitter
问题描述
在Angular网站上,他们有一个使用@Output() onVoted = new EventEmitter<boolean>();
相互交谈的父级和子级组件的示例.见下文.
On the Angular website they have an example of a Parent and Child component talking to each other using @Output() onVoted = new EventEmitter<boolean>();
. See below.
在此给定示例中,您是否需要退订EventEmitter以防止内存泄漏/膨胀?还是框架为您解决了这个问题?
In this given example, do you need to unsubscribe from the EventEmitter to prevent memory leaks/bloat? Or does the Framework take care of that for you?
component-interaction/src/app/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;
}
}
component-interaction/src/app/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网站上看到示例,但他们没有取消订阅,那么您为什么认为应该这样做?
If you see example on the Angular website and they don't unsubscribe then why do you think you should do it?
Angular会照顾它.
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);
,当它销毁组件时,它也会自动取消订阅输出:
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]();
因此,每次销毁您的angular指令时,都会为您处理所有订阅.
So every time you destroy your directive angular will dispose all subscription for you.
但是,如果您在代码中手动订阅EventEmitter
,则必须取消订阅.
But if you subscribe to EventEmitter
manually in code then you have to unsubscribe yourself.
这篇关于您是否需要退订@Output EventEmitter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!