我正在使用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>
答案 0 :(得分: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线程。