gpt4 book ai didi

javascript - 如何取消订阅 Angular 2中的多个订阅者

转载 作者:可可西里 更新时间:2023-11-01 01:55:20 32 4
gpt4 key购买 nike

我在另一个组件中有 shareService 和订阅:

import { Component, Input, OnDestroy } from '@angular/core';
import { MissionService } from './mission.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'my-astronaut',
template: `
<p>
{{astronaut}}: <strong>{{mission}}</strong>
<button
(click)="confirm()"
[disabled]="!announced || confirmed">
Confirm
</button>
</p>
`
})
export class AstronautComponent implements OnDestroy{
@Input() astronaut: string;
mission = "<no mission announced>";
confirmed = false;
announced = false;
subscription:Subscription;

constructor(private missionService: MissionService) {
this.subscription = missionService.missionAnnounced$.subscribe(
mission => {
this.mission = mission;
this.announced = true;
this.confirmed = false;
})




}
confirm() {
this.confirmed = true;
this.missionService.confirmMission(this.astronaut);
}
ngOnDestroy(){
// prevent memory leak when component destroyed
this.subscription.unsubscribe();

}
}

我想知道我的构造函数中是否有2个订阅者,如何在ngDestroy中取消订阅两次订阅者?我应该使用 subscription2:Subscription;? 和 ngDestroy this.subscription2.unsubscribe();?这是真的吗?

最佳答案

您可以在数组中的 ngOnDestroy() 中收集要立即取消订阅的订阅

export class AstronautComponent implements OnDestroy{
@Input() astronaut: string;
mission = "<no mission announced>";
confirmed = false;
announced = false;
subscriptions:Subscription[] = [];

constructor(private missionService: MissionService) {
this.subscriptions.push(missionService.missionAnnounced$.subscribe(
mission => {
this.mission = mission;
this.announced = true;
this.confirmed = false;
}));

this.subscriptions.push(fooService.fooObservable$.subscribe(
...
}));
}

confirm() {
this.confirmed = true;
this.missionService.confirmMission(this.astronaut);
}

ngOnDestroy(){
// prevent memory leak when component destroyed
this.subscriptions.forEach(s => s.unsubscribe());
}
}

关于javascript - 如何取消订阅 Angular 2中的多个订阅者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37695553/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com