Seb*_*ten 9 typescript angular
在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;
}
}
Run Code Online (Sandbox Code Playgroud)
组件的相互作用/ 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++;
}
}
Run Code Online (Sandbox Code Playgroud)
yur*_*zui 10
如果您在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);
Run Code Online (Sandbox Code Playgroud)
当它破坏组件时,它还会自动取消订阅输出订阅:
export function destroyView(view: ViewData) {
...
if (view.disposables) {
for (let i = 0; i < view.disposables.length; i++) {
view.disposables[i]();
Run Code Online (Sandbox Code Playgroud)
所以每次你销毁你的指令时,angular会为你处理所有订阅.
但是如果您EventEmitter在代码中手动订阅,则必须取消订阅.
| 归档时间: |
|
| 查看次数: |
3420 次 |
| 最近记录: |