2016-09-23 38 views
0

我有两个连续的订阅在角2 两个独立的可观察的问题,我想:从坐标两个角上的两个独立的观测顺序订阅2

  1. 获取地点
  2. 附加此位置我的JSON
  3. JSON发送到服务器

我做的事情是这样的,我相信错:

this._locationService.geocode(this.location.latitude, this.location.longitude). 
     subscribe(position => { 
      this.location.city = this.findAddressPart(position, "locality", "long"); 
      this.location.country = this.findAddressPart(position, "country", "long"); 
      this._locationService.updateLocation(this.location) 
       .subscribe(
        location => { 
         this.location = location; 
         this.submitted = true; 
         this.submitting = false; 
        } 
       ); 
     }); 

这样我的DOM在我实际获取位置后只更新5-10s。

+0

您是否尝试在角度区域运行此操作?使用this.zone.run(()=> {}) 您应该只在区域内运行位置分配 – galvan

+0

这是如何工作的? – Mantas

+0

请参阅这篇文章: http://www.joshmorony.com/understanding-zones-and-change-detection-in-ionic-2-angular-2/ – galvan

回答

0

您的解决方案需要更新多长时间似乎有问题。不幸的是,除非你重构你的_locationService如何使用数据,否则没有办法解决这个问题。目前,您有:从纬度和经度

  1. 获取地理编码
  2. 等待请求从一个位置完成从请求#1
  3. 集数据位置
  4. 获得更新数据
  5. 等待请求完成
  6. 集更新位置
  7. 更新DOM带更新位置

有两个链接在一起的请求。如果可能的话,我想这两个功能结合成一个呼叫后端,这样你可以调用像

this._locationService.geocode(this.location.latitude, this.location.longitude). 
     subscribe(location => { 
      this.location = location; 
      this.submitted = true; 
      this.submitting = false; 
     }); 

当然,如果您的服务器包含数据服务这一类型的请求这只会工作。如果您的服务器也必须进行HTTP调用,那么将其更改为上述内容将是没有意义的。

如果上述不可行,您可以在第一个请求完成后更新您的DOM。如果一切顺利,updateLocation函数将返回发送到服务器的相同位置,对吧?您可以使用本地可用的值更新DOM,而不是在第二个函数成功时更新DOM,只有在出现错误时才更改它们。这会让你的回复时间看起来快50%。像这样的东西。

this._locationService.geocode(this.location.latitude, this.location.longitude). 
     subscribe(position => { 
      this.location.city = this.findAddressPart(position, "locality", "long"); 
      this.location.country = this.findAddressPart(position, "country", "long"); 
      // SET DOM HERE using this.location values 
      this._locationService.updateLocation(this.location) 
       .subscribe(
        location => { 
         this.location = location; 
         // optionally SET DOM HERE again 
         this.submitted = true; 
         this.submitting = false; 
        }, 
        error => { 
         // SET DOM HERE reflecting error 
        } 
       ); 
     });