2016-09-26 6 views
2

に設定されているにもかかわらず、未定義です:initializeAngular2 - クラスプロパティは、それが私には、次の、非常にシンプルな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(); 
    } 
} 

を、私はコールバックとしてメソッドaddGraphicを設定しています。問題は、addGraphicメソッドの実行中にthis._drawが定義されていないことです。

ここで問題は何ですか?

+0

「初期化(geomotry)」はどこから呼び出されますか? – Martin

答えて

1

あなたは

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

ありがとうございます、あなたのソリューションは完全に正常に動作しています。 – netik

0

コンストラクタの代わりにngOnInit()にコードを移動します。 OnInitを実装する必要があります。

関連する問題