在方法中使用服务

时间:2016-05-10 15:38:25

标签: typescript angular

我正在尝试检索用户的地理位置,然后在单独的api调用中使用它。当我执行以下操作时,我收到此错误。该服务是'getLegislatorByLocation',它位于geoSuccess方法中。

  

EXCEPTION:TypeError:无法读取未定义的属性'getLegislatorByLocation'

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;
    }
}

我是否需要将服务注入方法?

1 个答案:

答案 0 :(得分: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);