2016-05-10 24 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; 
    } 
} 

难道我莫名其妙地需要注入服务进入方法?

+0

能否请你尝试'的console.log(_legislatorService)'添加到构造和发布它所打印的?除了使用构造函数进行注入之外,您不需要执行任何操作。还有其他的错误。您是否已将'LegislatorService'添加到'providers'? –

+0

'LegislatorService',如果你写的,需要'@Injectable'装饰器,并且应该在引导程序调用中添加到组件的提供者或提供者数组中。 – rinukkusu

+0

它拥有@Injectable装饰器。如果我在“ngOnInit()”中调用它,它工作正常当我将它移入geoSuccess()方法时发生问题 – dave

回答

2

你的代码输this.范围这一行

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

,如果你将其更改为

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

它应该工作。

神奇的是这保证了当geoSuccess()会从getCurrentPosition()内称为this仍将指向的LocalLegislatorsComponent当前实例,同时否则将指向getCurrentPosition()功能或徘徊无论geoSuccess正在从所谓的=>

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

看到周围工作的另一种方法是

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

完全像魔术一样。这有诀窍,谢谢你提供的信息非常丰富! – dave