2016-09-23 36 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 
        } 
       ); 
     });