netik netik - 2 months ago 13
TypeScript Question

Angular2 - Class property is undefined even though it is being set

I'm having the following, very simple angular2 Service:

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


In
initialize
, I'm setting the method
addGraphic
as the callback. Now the problem is, that within the
addGraphic
method execution,
this._draw
is undefined.

What's the problem here?

Answer

If you pass a method reference like

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

the reference to this points to the caller function.

If you use instead

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

it should work as expected.

Alternatively you can also use arrow functions but this requires to repeat the parameters (if there need any to be passed).

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