我有另一个组件的shareService和subscribe:
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());
}
}