我试图检索用户的地理位置,然后在单独的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;
}
}
难道我莫名其妙地需要注入服务进入方法?
能否请你尝试'的console.log(_legislatorService)'添加到构造和发布它所打印的?除了使用构造函数进行注入之外,您不需要执行任何操作。还有其他的错误。您是否已将'LegislatorService'添加到'providers'? –
'LegislatorService',如果你写的,需要'@Injectable'装饰器,并且应该在引导程序调用中添加到组件的提供者或提供者数组中。 – rinukkusu
它拥有@Injectable装饰器。如果我在“ngOnInit()”中调用它,它工作正常当我将它移入geoSuccess()方法时发生问题 – dave