netik
netik

Reputation: 1826

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?

Upvotes: 2

Views: 76

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657198

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));

Upvotes: 1

John Baird
John Baird

Reputation: 2676

Move the code to ngOnInit() instead of the constructor. You'll have to implement OnInit.

Upvotes: 0

Related Questions