2017-07-09 7 views
0

ジオコード関数の終了後にFirebaseデータベースを更新するメソッドを記述しようとしています。 Angular2でコードを書いているので、Firebaseデータベースがコンストラクタで定義されています。私はこの問題が非同期関数であることを理解していますが、これについてどうやって行くのかは分かりません。ここに私のコードは次のとおりです。Googleのジオコード非同期メソッドでのFirebaseの更新

geocoding(callback){ 
var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({'address': this.loc}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     callback([results[0].geometry.location.lat(), results[0].geometry.location.lng()]); 
    } else { 
     this.lat = 0; 
    } 
    }); 
} 

と:

geocode(){ 
this.geocoding(function(latLng){ 
    this.db.object('users/' + this.auth.id).update({ 
    lat: latLng[0], 
    lng: latLng[1] 
    }); 
}); 
} 

答えて

1

私はそれを行う方法を考え出しました。

geocode(address){ 
    return new Promise(function(resolve,reject){ 
     var geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({'address': address}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
      resolve(results); 
      } else { 
      this.lat = 0; 
      } 
     }); 
     }); 
    } 

と::

this.geocode(this.loc).then(results => { 
     this.db.object('users/' + this.auth.id).update({ 
     lat: results[0].geometry.location.lat(), 
     lng: results[0].geometry.location.lng() 
     }); 
    }); 
あなたが約束を使用する必要が判明し、ここで働くのコードです
関連する問題