angular - 如果 rxjs observable 不对变化做出反应,它的目的是什么?
问题描述
我有一个项目数组,我使用of
.
可观察对象是在填充数组之前创建的。
最终填充数组时,不会调用observable callback
传递给的对象。subscribe
据我了解,observable
仅将其callback
用于列表中已有的项目,在我看来,这使得它变得多余。
我有一个案例,我在*ngFor
withasync
管道中使用这个 observable,这个反应正确,但是当我将 observable传递data source
给 amat-table
或者我将我传递callback
给subscribe
函数时,当列表最终被填充时,我什么也得不到.
管道在幕后做了什么async
,而我失踪了?
export class DiscoveryService {
private deviceList: DeviceModel[] = [];
constructor() {
}
getDeviceList(): void {
// Get devices from server and push them in the deviceList
}
observeDeviceList(): Observable<DeviceModel[]> {
return of(this.deviceList);
}
}
export class DeviceListComponent implements OnInit {
deviceList$: Observable<DeviceModel[]>;
constructor(private discoveryService: DiscoveryService) { }
ngOnInit() {
this.deviceList$ = this.discoveryService.observeDeviceList();
// This callback get's called only once at the beginning, with an empty list
this.deviceList$.subscribe(devices => console.log('got devices: ' , devices));
// When the devices are retrieved from the server, the callback
//from the above subscription is not triggered again
this.discoveryService.getDeviceListx();
}
}
管道得到正确更新,async
但我想这可能是因为ngOnInit
在运行之前调用了*ngFor
。我不确定。
<mat-nav-list *ngFor="let device of deviceList$ | async">
解决方案
您的 observable 不会对更改做出反应,因为它是从静态数组创建的,使用of
它只发出一次。这是您可以做的事情。
发现服务
export class DiscoveryService {
private _deviceList$ = new BehaviorSubject<DeviceModel[]>([]);
construct() {
this.fetchDeviceList();
}
get deviceList$() {
return this._deviceList$.asObservable();
}
fetchDeviceList() {
this.http.get<DeviceModel[]>('yourUrl').pipe(
tap((list: DeviceModel[]) => this._deviceList$.next(list))
).subscribe();
}
}
设备列表组件
export class DeviceListComponent implements OnInit {
private _deviceList$: Observable<DeviceModel[]>;
constructor(private discoveryService: DiscoveryService) { }
ngOnInit() {
this._deviceList$ = this.discoveryService.deviceList$;
}
}
那么这在您的模板中应该可以正常工作
<mat-nav-list *ngFor="let device of _deviceList$ | async">
推荐阅读
- c - Makefile 找不到规则
- hadoop - 如何在不编码的情况下查看/创建 kylin cube 的 hbase 表
- c# - 带有.net核心模型的Angular 6未绑定
- r - 使用 R 比较两个文本文件
- java - ARCore – 来自 arFragment 的图像与片段的显示不同
- python - 如何将数据写入 .txt 文件,而不写入 2 次
- java - 我可以在初始化设置的内容视图后更改 Android Button 的样式吗?
- python - 运行 python 项目时出现 web_socket 错误
- c# - 如何获得执行的声明成员?
- aws-lambda - 如果 Lambda 函数抛出错误(不是超时),如何向 DLQ 发送错误?