异步回调中的BehaviorSubject未在HTML视图ionic中更新



我正试图让一个变量在Ionic应用程序的前端更新其值。如果我触摸任何离子按钮,变量会在前端更新,但当其值更新时不会更新。

在.html文件中,我得到了:

<p>{{ scantext$ | async }}</p>

在.ts文件中,我得到了:

export class HomePage {
....
this.bluetoothle.startScan(scanparams).subscribe(this.startScanSub);
....
startScanSub = {
next: device => this.addToText('subscribe:' + JSON.stringify(device)),
error: err => this.addToText('subscribe: ' + JSON.stringify(err)),
complete: () => this.addToText('subscribe Complete'),
};
scantext$: BehaviorSubject<string> = new BehaviorSubject('init');
addToText(device){
this.scantext$.next(device);
console.log(device);
}
....

我确信变量正在更改其值,因为我可以在订阅中看到日志信息。然而,在前端,我看不到变量是如何改变其值的,除非我触摸应用程序中的按钮。

如何在前端自动更改变量?

我确信变量正在更改其值,因为我可以看到作为来自订阅的信息登录。然而,在前端我看不到变量如何更改其值,除非我触摸应用程序中的按钮。

看起来数据没有被跟踪。

有一些解决方案,使用NgZoneChangeDetectorRef

NgZone

export class HomePage {
constructor(private _zone: NgZone) {
...
}
}
addToText(device) {
this._zone.run(() => this.scantext$.next(device));
console.log(device); 
}

变更检测器参考

import { ChangeDetectorRef } from '@angular/core';
export class HomePage {
constructor (private _cdr: ChangeDetectorRef) {
...
}
}
addToText(device){
this.scantext$.next(device);
console.log(device);
this._cdr.detectChanges();
}

最新更新