什么导致可观察的返回结果与在浏览器中显示结果之间的延迟?

时间:2017-01-06 00:14:09

标签: angular observable geofire

我使用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

1 个答案:

答案 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之前加载的?