Typescript 在方法中使用服务

Typescript 在方法中使用服务,typescript,angular,Typescript,Angular,我试图检索用户的地理位置,然后在单独的api调用中使用它。当我执行以下操作时,会出现此错误。该服务是“GetLegitorByLocation”,它位于geoSuccess方法中 异常:TypeError:无法读取未定义的属性“GetLegitorByLocation” 导出类LocalLegitorComponent实现OnInit{ 构造器(私人立法服务:立法服务){ } ngOnInit():void{ 这是geofinduster(); } geoFindUser():void{ 如果(

我试图检索用户的地理位置,然后在单独的api调用中使用它。当我执行以下操作时,会出现此错误。该服务是“GetLegitorByLocation”,它位于geoSuccess方法中

异常:TypeError:无法读取未定义的属性“GetLegitorByLocation”

导出类LocalLegitorComponent实现OnInit{
构造器(私人立法服务:立法服务){
}
ngOnInit():void{
这是geofinduster();
}
geoFindUser():void{
如果(!navigator.geolocation){
this.geoSupport=false;
返回;
}
navigator.geolocation.getCurrentPosition(this.geosucces,this.georror);
}
地理成功(位置):无效{
this.geoSupport=true;
this.latitude=position.coords.latitude;
this.longitude=position.coords.longitude;
this.\u legitorservice.getlegitorbylocation(this.latitude,this.longitude)
.subscribe(legitors=>this.legitors=legitors,error=>this.errorMessage=error);
}
geoError():void{
console.log('无法检索位置');
this.geoSupport=false;
}
}

我是否需要以某种方式将服务注入到方法中?

您的代码将丢失这一行的
作用域

navigator.geolocation.getCurrentPosition(this.geoSuccess, this.geoError);
如果你把它改成

navigator.geolocation.getCurrentPosition((pos) => this.geoSuccess(pos), this.geoError);
它应该会起作用

神奇的是
=>
它确保了当从
getCurrentPosition()
中调用
geosucces()
时,该
仍将指向
locallegitorComponent
的当前实例,否则它将指向
getCurrentPosition()
函数或调用geosucces的位置

另见

另一种解决方法是

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

您的代码将丢失这一行的
this.
作用域

navigator.geolocation.getCurrentPosition(this.geoSuccess, this.geoError);
如果你把它改成

navigator.geolocation.getCurrentPosition((pos) => this.geoSuccess(pos), this.geoError);
它应该会起作用

神奇的是
=>
它确保了当从
getCurrentPosition()
中调用
geosucces()
时,该
仍将指向
locallegitorComponent
的当前实例,否则它将指向
getCurrentPosition()
函数或调用geosucces的位置

另见

另一种解决方法是

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

您可以尝试将
console.log(\u legitorservice)
添加到构造函数中并发布它打印的内容吗?除了使用构造函数进行注入,您不需要做任何事情。还有别的问题。您是否将
立法者服务
添加到
提供者
的任何位置?
立法者服务
如果由您编写,则需要
@Injectable
装饰器,并且应该添加到您的组件的提供者或引导调用中的提供者数组中。它确实具有@Injectable装饰器。如果我在“ngOnInit()”中调用它,效果会很好。问题发生在我将其移动到geoSuccess()方法时。请尝试将
console.log(\u legitorservice)
添加到构造函数并发布它打印的内容好吗?除了使用构造函数进行注入,您不需要做任何事情。还有别的问题。您是否将
立法者服务
添加到
提供者
的任何位置?
立法者服务
如果由您编写,则需要
@Injectable
装饰器,并且应该添加到您的组件的提供者或引导调用中的提供者数组中。它确实具有@Injectable装饰器。如果我在“ngOnInit()”中调用它,效果会很好。问题发生在我将它移动到geoSuccess()方法中时,就像magic一样。这就成功了,谢谢你提供的信息丰富的回复!就像魔法一样。这就成功了,谢谢你提供的信息丰富的回复!