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



我正在用nativescriptpedometer插件构建一个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线程。

最新更新