javascript - Angular2 - 类属性未定义,即使它正在设置

标签 javascript angular typescript

我有以下非常简单的 angular2 服务:

@Injectable()
export class DrawingService {
    private _draw:Draw;

    constructor(private mapSvc:MapService) {}

    initialize(geometry: GeometryType):void {
        this._draw = new Draw(this.mapSvc.getMap());
        this._draw.on("draw-end", this.addGraphic);
        this._draw.activate(geometry);
    }


    addGraphic(evt):void {
        this._draw.deactivate();
    }
}

initialize 中,我将方法addGraphic 设置为回调。现在的问题是,在 addGraphic 方法执行中,this._draw 未定义。

这里有什么问题?

最佳答案

如果你传递一个像这样的方法引用

   this._draw.on("draw-end", this.addGraphic);

this 的引用指向调用者函数。

如果你改用

   this._draw.on("draw-end", this.addGraphic.bind(this));

它应该按预期工作。

或者,您也可以使用箭头函数,但这需要重复参数(如果需要传递任何参数)。

   this._draw.on("draw-end", (param) => this.addGraphic(param));

关于javascript - Angular2 - 类属性未定义,即使它正在设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39699780/

相关文章:

javascript - 如何在HTML中分别操作两组选项卡?

javascript - HighCharts:一个传奇,两个图表

javascript - 如何正确使用javascript promises? ( ionic 和 Cordova 相关)

node.js - 无服务器 Typescript 插件将我所有的 lambda 函数打包到一个 zip 存档中

javascript - 通过 Typescript 类扩展 JavaScript 对象原型(prototype)

Angular typescript 连接数字而不是相加

javascript - jQuery 脚本只执行一次

javascript - 自定义谷歌地图无法正确渲染,分辨率不佳

angular - 空注入(inject)器错误 : No provider for NgZone when referencing a custom npm package

angular - 在服务中注入(inject)组件的实例