Observable中的多个Observable未按预期解析

时间:2017-12-24 15:20:28

标签: angular observable rxjs5

我看到一个简单的问题,我对Rx没有足够的经验。

ngOnInit() {
this.agentService.getAllAgents().subscribe((agents: Agent[]) => {
  this.agents = agents.sort((x: Agent, y: Agent) =>
    Number(new Date(x.date)) - Number(new Date(y.date)));

  for (const agent of this.agents) {
    forkJoin(this.geoLocator.find(agent.address)).subscribe(results => {
      for (const coordinates of results) {
        agent.distance = this.getDistance(<Coordinates>environment.google.COORDINATES, coordinates, Unit.km);
      }
    });
  }
  console.log(this.agents[0]);
  console.log(JSON.stringify(this.agents[0]); 
});

}

enter image description here

这是我得到的结果。

问题是如何以及为何?

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
 public find(agent: Agent): Observable<Agent> {
    return this.http.get<Agent>(`${environment.google.BASE_URL}${agent.address}`)
      .map(response => {
        const coordinates = <Coordinates> {
          latitude: response['results'][0].geometry.location.lat,
          longitude: response['results'][0].geometry.location.lng
        };
        agent.distance = this.getDistance(<Coordinates>environment.google.COORDINATES, coordinates, Unit.km);
        return agent;
      });
  }
&#13;
&#13;
&#13;