是什么导致可观察到的返回结果和在浏览器中显示结果之间的滞后?

What's causing lag between observable returning result and displaying result in browser?

我正在使用 Angular 2 和 GeoFire 来显示某个区域附近的专业人士。我创建了一个服务来使用 GeoFire return 观察到的专业人士列表,但是我在获取该列表和显示它之间遇到了巨大的延迟。

这是我让专业人士为我服务的方法:

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

听起来 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 之前加载?