在 NativeScript Angular 应用程序中使用 属性 绑定延迟

Delay with property binding in NativeScript Angular app

我正在使用 nativescript-pedometer 插件构建一个 NativeScript Angular 应用程序。我设置了一个 Observable 来报告新的步骤。当报告新步骤时,我将数字记录到控制台,更新 Home 组件上的 属性 并调用 ApplicationRef.tick().

UI 中的数字确实发生了变化,但只有在延迟至少五秒,有时长达一分钟之后,从我在控制台中看到它的时间到我看到它的时间在 UI.

而不是 ApplicationRef.tick() 我还尝试了 NgZone.run(callback)ChangeDetectorRef.detectChanges()。他们中的任何一个都有延迟。如果我不包括其中任何一个,UI 永远不会更新。

我应该提一下,我只在 iOS 设备上测试过,不确定问题是否会发生在 Android。

这里是home.component.ts:

import { Component, OnInit, ApplicationRef } from "@angular/core";
import { Pedometer } from "nativescript-pedometer";
import { Observable } from "rxjs";
import { take } from "rxjs/operators";

@Component({
  selector: "Home",
  moduleId: module.id,
  templateUrl: "./home.component.html"
})
export class HomeComponent implements OnInit {
  numSteps: number;
  pedometer: Pedometer;

  constructor(private applicationRef: ApplicationRef) {}

  ngOnInit(): void {
    this.numSteps = 0;
    this.pedometer = new Pedometer();

    this.startUpdates().subscribe(response => {
      console.log('New step count received from pedometer:');
      console.log(response.steps);
      this.numSteps = response.steps;
      this.applicationRef.tick();
    });
  }

  startUpdates(): Observable<any> {
    return Observable.create(observer => {
      this.pedometer.startUpdates({
        onUpdate: result => observer.next(result)
      });
    }).pipe(take(25));
  }
}

这里是 home.component.html:

<StackLayout>
    <Label text="Number of steps is:"></Label>
    <Label [text]="numSteps"></Label>
</StackLayout>

onUpdate 从后台线程调用,Angular 在 UI 线程上调用。试试这个,

startUpdates(): Observable<any> {
 return Observable.create(observer => {
  this.pedometer.startUpdates({
    onUpdate: result => Promise.resolve().then(() => observer.next(result))
  });
 }).pipe(take(25));
}

Promise.resolve() 强制块进入 UI 线程。