【问题标题】:Delay with property binding in NativeScript Angular appNativeScript Angular 应用程序中的属性绑定延迟
【发布时间】:2018-12-09 15:44:53
【问题描述】:

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

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

除了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>

【问题讨论】:

    标签: angular nativescript property-binding


    【解决方案1】:

    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 线程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 2018-06-14
      相关资源
      最近更新 更多