【问题标题】:BehaviorSubject in asynchronous callback not updating in HTML view ionic异步回调中的 BehaviorSubject 在 HTML 视图中未更新
【发布时间】:2020-05-10 04:27:16
【问题描述】:

我正在尝试让一个变量在 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);
}
....

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

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

【问题讨论】:

  • 你能写出你当前的结果吗?控制台中显示的内容以及单击前您可以在屏幕上看到的内容?还有'init'文本吗?
  • 在我点击之前,我可以看到“init”。当我单击时,订阅发生,1 或 2 秒后,“init”变为“{“status”:“scanStarted”}”,这似乎工作正常。但是,在扫描期间,console.log(device);多次触发,但文本保持不变(“{“status”:“scanStarted”}“)。我包装了 this.scantext$.next(device);使用 console.log("之前");和 console.log("After");我可以看到两个日志,所以 this.scantext$.next(device);必须触发。

标签: html angular asynchronous ionic-framework rxjs


【解决方案1】:

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

似乎没有跟踪数据。

有一些解决方案,使用NgZoneChangeDetectorRef

NgZone

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

ChangeDetectorRef

import { ChangeDetectorRef } from '@angular/core';

export class HomePage {
  constructor (private _cdr: ChangeDetectorRef) {
    ...
  }
}
addToText(device){
   this.scantext$.next(device);
   console.log(device);
   this._cdr.detectChanges();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多