我有以下非常简单的 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/