2016-12-10 4 views
1

Ich baue ein Formular Form Builder verwenden:Wie dies in Callback-Formbuilder-Validator Zugriff

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

Der Validator Brauch für die Postleitzahl wie folgt aussieht:

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; 
} 

Nach jedem der Rückruf ändern wird aufgerufen, aber this ist undefiniert. Also musste ich einen Weg finden, um darauf zuzugreifen. Alles funktioniert gut, sieht aber nicht gut aus. Was wäre in diesem Fall am besten?

Antwort

1

Ich würde stattdessen den HTTP-Request-Aufruf in Form valueChanges-Ereignis setzen.

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)); 
      } 
     }); 
} 
}); 

OR könnten Sie denken, eine separate Richtlinie wie das Tutorial zu schaffen here