【问题标题】:Angular: RxJS Observable only updating on timeoutAngular:RxJS Observable 仅在超时时更新
【发布时间】:2016-09-15 03:02:10
【问题描述】:

我有一个可注入服务,它执行 BLE 扫描并将结果通过可观察到的页面组件流式传输到页面组件,然后将其存储在局部变量中并显示(理论上)。

问题是来自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);
    });
}

【问题讨论】:

    标签: angular typescript ionic-framework rxjs


    【解决方案1】:

    来自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();   // <---------
        });
    }
    

    另见Triggering Angular2 change detection manually

    【讨论】:

      猜你喜欢
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多