2017-07-05 6 views
0

TypeScriptで書かれたサービスがあります。このサービスを利用Typescript AngularJS 'this'は定義されていません

export default class AServiceClass { 

    constructor(private $http: ng.IHttpService, ...) {} 

    method1(data : any) : void { 
     this.$http(...) 
    } 

    method2(data : any) : void { 
     this.$http(...) 
    } 
} 

そして、私はコントローラクラスを持っている、::ような何か - this is undefind

export default class AControllerClass { 

    constructor(private aService: AServiceClass, ...) {} 

    $onInit(){ 

     let method = true ? this.aService.method1 : this.aService.method2; 
     method({ ... data ... }); 
    } 
} 

サービスメソッドは例外をスローします。 this.aService.method1({ ... data ... })のように使用すると、すべて問題ありません。私はmethod.bind(aService)({ ... data ... })またはmethod.call(aService, { ... data ... })を行うことができますが、なぜスコープの違いがありますか?

Thx。

+0

この代わりに$ ngInitののOnInit $を、動作するはずです。角度1が私のために少し戻っているのは分かりませんが、試してみてください。これは$ onInit = function(){あなたのコード}です。 – Doomenik

+0

ああ、これは、例ではtypoだった、ofc $ onInit。 Thx – Kindzoku

+0

それでも "これは未定"です。 – Doomenik

答えて

1

method1メソッドがコンテキストなしで呼び出されるため、その内部のthisは定義されません。あなたはbindを使用してコンテキストをバインド明示的コンテキストとしてaServiceオブジェクトとそれを呼び出すか、明示的にcallまたはapplyを使用してコンテキストを設定したりする必要があります。

this.aService.method1(); // `this` will be aService inside `method1` 

method.call(aService, args); 

method.apply(aService, [args]); 

// Or bind using `bind`: 

let method = true ? this.aService.method1.bind(this.aService) : this.aService.method2.bind(this.aService); 

method(); 
+0

ああ、thx。これを知らない。恥ずかしい。 :) – Kindzoku

関連する問題