2016-11-14 118 views
-1

我有了調用事件點擊功能按鈕組件:angular2的onclick調用方法服務

<button pButton type="button" label="Add EchoBeacon" (click)="insertPoint()"> 
constructor(private mappaService: MappaService) {} 
... 
insertPoint() { 
    this.map.removeInteraction(this.interaction); 
    this.select.getFeatures().clear(); 
    this.map.removeInteraction(this.select); 
    this.interaction = new ol.interaction.Draw({ 
     type: /** @type {ol.geom.GeometryType} */ 'Point', 
     source: this.echoBeacons.getSource() 
    }); 
    this.map.addInteraction(this.interaction); 
    this.interaction.on('drawend', function(e) { 
     var feature = e.feature; 
     var geometry = feature.getGeometry(); 
     this.coordinates = geometry.getCoordinates(); 
     this.mappaService.savePoint(this.coordinates[0], this.coordinates[1]) 
     .subscribe(
      data => console.log('Added'), 
      error => console.error('Error: ' + error), 
      () => console.log('Completed!') 
     ); 

} 

,這是該方法的服務:

savePoint(x: number, y :number): Observable<any[]>{ 
    let headers  = new Headers({ 'Content-Type': 'application/json' }); 
    let options  = new RequestOptions({ headers: headers }); 
    let serverPostDbUrl ="http://172.16.32.1:3000/beacon"; 
    let body = `{"x": ${x}, "y": ${y}}`; 
    return this.http.post(`${serverPostDbUrl}`, body, options) 
    .map((res:Response) => res.json()) 
    .catch((error:any) => Observable.throw(error.json().error || "Server error")); 

} 

,但是當我點擊按鈕,控制檯記錄我「無法讀取未定義的屬性」,如mappaService未在insertPoint()函數中定義

+0

的可能的複製[角2:自舉開關不改變可變的值](http://stackoverflow.com/questions/40517580/angular-2-bootstrap-switch-not-changing-value-of-變量) – Fiddles

回答

2

您的問題是與以下行:this.interaction.on('drawend', function(e) {

使用常規函數定義將更改此上下文,以便它不再是組件/服務。您將需要使用Arrow Functions來維護this

即。

this.interaction.on('drawend', (e) => { 
+0

謝謝!有用 –