2016-05-10 8 views
0

私はユーザーのジオロケーションを取得して、それを別のAPI呼び出しで使用しようとしています。私が次のことをすると、このエラーが出ます。サービスは 'getLegislatorByLocation'で、geoSuccessメソッドにあります。メソッド内のサービスを使用する

EXCEPTION: TypeError: Cannot read property 'getLegislatorByLocation' of undefined

export class LocalLegislatorsComponent implements OnInit { 

    constructor(private _legislatorService: LegislatorService) { 

    } 

    ngOnInit(): void {  
     this.geoFindUser();      
    } 



    geoFindUser(): void { 

     if (!navigator.geolocation) { 
      this.geoSupport = false; 
      return; 
     } 

     navigator.geolocation.getCurrentPosition(this.geoSuccess, this.geoError); 
    } 

    geoSuccess(position): void { 
     this.geoSupport = true; 
     this.latitude = position.coords.latitude; 
     this.longitude = position.coords.longitude; 

     this._legislatorService.getLegislatorByLocation(this.latitude, this.longitude) 
      .subscribe(legislators => this.legislators = legislators, error => this.errorMessage = <any>error); 
    } 

    geoError(): void { 
     console.log('Unable to retrieve location'); 
     this.geoSupport = false; 
    } 
} 

私が何とかする方法にサービスを注入する必要がありますか?あなたはそれが動作するはず

navigator.geolocation.getCurrentPosition((pos) => this.geoSuccess(pos), this.geoError); 

にそれを変更した場合

+0

だろうあなたはコンストラクタに 'はconsole.log(_legislatorServiceを)'追加し、それを印刷し何を投稿してみていただけますか?あなたはコンストラクタを使って注入する以外何もする必要はありません。それ以外の何かが間違っています。 'LegislatorService'をどこのプロバイダにも追加しましたか? –

+0

'LegislatorService'は、あなたが書いた場合、' @Ijectable'デコレータを必要とし、あなたのブートストラップ呼び出しであなたのコンポーネントのプロバイダやプロバイダ配列に追加する必要があります。 – rinukkusu

+0

@Ajectableデコレータがあります。 "ngOnInit()"で呼び出すとうまくいきます。geoSuccess()メソッドに移動したときに問題が発生しました。 – dave

答えて

2

あなたのコードは、この行

navigator.geolocation.getCurrentPosition(this.geoSuccess, this.geoError); 

this.スコープを失います。

魔法geoSuccess()getCurrentPosition()内から呼び出されたときに、それ以外の場合はgetCurrentPosition()関数を指しますまたはwhereever geoSuccessがから呼び出されている間thisまだLocalLegislatorsComponentの現在のインスタンスを指すことを保証=>あります。

も参照してくださいhttps://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

周りの作業のもう一つの方法は、

navigator.geolocation.getCurrentPosition(this.geoSuccess.bind(this), this.geoError); 
+1

まるで魔法のようです。これはトリックでした、非常に有益な応答に感謝! – dave

関連する問題