2016-12-10 39 views
1

我使用表單生成器建立一個形式:如何訪問這formbuilder驗證回調

public searchMapForm = this.formBuilder.group({ 
    country: ["DE"], 
    postcode: ["13347", this.searchCont], 
    this: [this] 
}); 

的郵政編碼自定義驗證的樣子:

private searchCont(c) { 

    if(!c || !c.value || c.value.length < 4) return { toShort: { valid: false } }; 

    var __this = c._parent && c._parent.controls.this.value; // this look too complicated 

    if(__this && __this.http) { 
     __this.http.get('http://nominatim.openstreetmap.org/search?format=json&addressdetails=1&limit=5&postalcode=' + c.value + '&countrycodes=' + c._parent.controls.country.value).subscribe(res => { 
      let l = res.json()[0]; 

      if(l) { 
       __this.map.setView([l.lat, l.lon], 13, { animate: true }) 
       __this.markers.map(m => { m.remove(); }) 
       __this.markers = []; 
       __this.markers.push(L.marker([l.lat, l.lon]).addTo(__this.map)); 
      } 
     }); 
    } 

    return null; 
} 

每次改變後,調用回調,但this未定義。所以我必須找到一種方法來訪問它。一切正常,但不好看。在這種情況下最好的做法是什麼?

回答

1

我會把http請求調用放在form的valueChanges事件中。

searchMapForm.valueChanges.subscribe(e=>{ 
if(this.searchMapForm.controls['postcode'].valid && !this.searchMapForm.controls['postcode'].pristine){ 
this.http.get('http://nominatim.openstreetmap.org/search?format=json&addressdetails=1&limit=5&postalcode=' + e.postcode + '&countrycodes=' + e.country).subscribe(res => { 
      let l = res.json()[0]; 

      if(l) { 
       this.map.setView([l.lat, l.lon], 13, { animate: true }) 
       this.markers.map(m => { m.remove(); }) 
       this.markers = []; 
       this.markers.push(L.marker([l.lat, l.lon]).addTo(this.map)); 
      } 
     }); 
} 
}); 

,或者你可以想創建一個單獨的指令,像本教程的here