我正在使用nativescript-pedometer插件构建NativeScript Angular应用程序 . 我设置了一个Observable来报告新的步骤 . 报告新步骤时,我将数字记录到控制台,更新主组件上的属性并调用 ApplicationRef.tick()
.
UI中的数字确实会发生变化,但是只有在我在控制台中看到它的时间和我在UI中看到的时间之间至少延迟五秒(有时甚至一分钟)之后 .
而不是 ApplicationRef.tick()
我也尝试了 NgZone.run(callback)
和 ChangeDetectorRef.detectChanges()
. 有's a delay with any of them. If I don' t包含其中任何一个,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>
1 回答
onUpdate
从后台线程调用,Angular在UI线程上调用 . 试试这个,Promise.resolve()
强制该块进入UI线程 .