【问题标题】:angular2 onclick call method serviceangular2 onclick 调用方法服务
【发布时间】:2016-11-14 23:58:41
【问题描述】:

我有一个按钮组件,它必须在事件点击时调用函数:

<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() 函数中定义

【问题讨论】:

标签: javascript angular typescript onclick http-post


【解决方案1】:

你的问题在于这一行:this.interaction.on('drawend', function(e) {

使用常规函数定义将改变 this 的上下文,使其不再是组件/服务。您将需要使用Arrow Functions 来维护this

即。

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

【讨论】:

    猜你喜欢
    • 2018-06-01
    • 2016-10-13
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多