这是我已经拥有的代码:
device.service.ts
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DeviceService {
deviceList: any;
private deviceListSource = new BehaviorSubject(this.deviceList);
currentDeviceList = this.deviceListSource.asObservable();
constructor(){}
getDevices(): void {
this.http.get<any>('https://........')
.subscribe(data => {
this.deviceListSource.next(data.data);
}, error => console.log('Could not GET devices.'));
}
我的对话框组件如下所示:
devices.component.ts
ngOnInit() {
this.deviceService.getDevices();
this.deviceService.currentDeviceList.subscribe(data => {
console.log(data)
});
}
这非常适合在多个组件之间共享某些值。当我关闭对话框(为devices.component.ts
)并再次打开它而不重新加载整个页面时,console.log(data)
命令的执行次数与打开/关闭对话框的次数相同。因此,当我打开对话框时,它会依次.next()
预订由服务添加的所有值。但我希望对话框仅预订该服务添加的最后一个值。
据我所知,BehaviorSubject
正是用于此用例的。有什么我想念的吗?还是有另一种(更好)的方法来实现这一目标?
答案 0 :(得分:1)
先前的下标仍保留该流,因此您需要在销毁设备组件之前清除它。一种方法是:
devices.component.ts
destroy$ = new Subject();
ngOnInit() {
this.deviceService.getDevices();
this.deviceService.currentDeviceList
.pipe(takeUntil(this.destroy$)) // takUntil from rxjs
.subscribe(data => {
console.log(data)
});
}
ngOnDestroy(){
this.destroy$.next();
this.destroy$.complete(); // always call complete for guaranteed subscription removal
}
答案 1 :(得分:0)
关闭对话框后,立即终止订阅。
someSubscription: Subscription
ngOnInit() {
this.deviceService.getDevices();
this.someSubscription = this.deviceService.currentDeviceList.subscribe(data => {
console.log(data)
});
}
ngOnDestroy() {
if (this.someSubscription) {
this.someSubscription .unsubscribe();
}
}