我使用Angular 2和GeoFire来显示某个区域内的附近专业人士。我创建了一个服务,使用GeoFire返回一个专业人士列表的可观察量,但是我在获取该列表并显示它之间会有很大的延迟。
这是让我的服务专业人员的方法:
public getKeysFromGeoQuery(): Observable<any> {
var keys = new Array();
return Observable.create(observer => {
this.geoQuery.on("key_entered", (key, location, distance) => {
keys.push(key);
observer.next(keys);
});
this.geoQuery.on("key_exited", (key, location, distance) => {
var index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
}
observer.next(keys);
});
});
}
这是我使用该服务的测试组件:
import { Component } from '@angular/core';
import { LocationService } from '../../core/location.service';
import { Observable, Observer } from 'rxjs';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent {
mapCenter = [34.021256, -118.403630];
searchRadius = 4;
result;
error;
time;
constructor(private locationService: LocationService) {
const startTime = Date.now();
this.locationService.getGeoQuery({ center: this.mapCenter, radius: this.searchRadius });
this.locationService.getKeysFromGeoQuery()
.subscribe(keys => {
this.result = keys;
console.log("keys: ", this.result);
this.time = Date.now() - startTime;
console.log("time: ", this.time);
});
}
}
test.component.html:
<p>Result: {{result}} </p>
<p>Time: {{time}} </p>
<p>Error: {{error}} </p>
在我的控制台中,它显示在500毫秒内检索到的密钥。但是,浏览器在3-4秒后才会显示结果。有谁知道导致这种延迟的原因是什么? Screen and console
答案 0 :(得分:1)
听起来GeoFire on
事件正在区域外被解雇。
您可以通过注入ChangeDetectorRef
并明确触发更改检测来验证这一点:
import { ChangeDetectorRef } from '@angular/core';
...
@Component({
...
})
export class TestComponent {
...
constructor(
private locationService: LocationService,
private changeDetectorRef: ChangeDetectorRef
) {
...
this.locationService.getKeysFromGeoQuery()
.subscribe(keys => {
this.result = keys;
console.log("keys: ", this.result);
this.time = Date.now() - startTime;
console.log("time: ", this.time);
this.changeDetectorRef.detectChanges();
});
}
}
如果事件是在区域外触发的,则可能与Firebase和GeoFire脚本如何合并到您的构建中有关。也许它们是在zone.js
之前加载的?