我有一个可注射服务,它执行BLE扫描并通过一个observable将结果流式传输到页面组件,然后将其存储在局部变量中并显示(理论上)。
问题是来自startScanWithOptions
方法的更新不会导致视图更新,而来自setInterval
方法的更新会导致更新视图。当所有更新都写入控制台时,更新将进入页面组件,但在setInterval
更新导致渲染之前不会显示。
来自注射服务:
start() {
this.connections$ = new Observable((observer) => {
if (this.blePlugin) {
this.blePlugin.startScanWithOptions(
[],
{ reportDuplicates: true },
(result) => this.observableScanResult(result, observer)
);
}
setInterval(()=>{this.observableScanResult({rssi: 100}, observer)}, 1000);
});
return this.connections$;
}
private observableScanResult(result, observer) {
observer.next(result);
}
从页面组件:
private startSelection() {
console.log('Scan Starting');
this.connectionSource = this.connection.start();
this.connectionSub = this.connectionSource.subscribe((result) => {
this.test.push(result.rssi);
console.log(this.test);
});
}
答案 0 :(得分:2)
来自startScanWithOptions()
方法的更新可能在Angular区域之外运行,这意味着Zone.js不会对异步事件进行猴子修补,例如setTimeout()
。
在startSelection()
中,在subscribe()
回调中手动触发更改检测:
export class MyComponent {
constructor(private _cdRef:ChangeDetectorRef) {}
private startSelection() {
console.log('Scan Starting');
this.connectionSource = this.connection.start();
this.connectionSub = this.connectionSource.subscribe((result) => {
this.test.push(result.rssi);
console.log(this.test);
this._cdRef.detectChanges(); // <---------
});
}