dave
dave

Reputation: 205

using a service in a method

I'm trying to retrieve the user's geolocation and then use it in a separate api call. When I do the following I get this error. The service is 'getLegislatorByLocation' and it's in the geoSuccess method.

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

Do I somehow need to inject the service into the method?

Upvotes: 0

Views: 35

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657078

Your code loses the this. scope with this line

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

if you change it to

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

it should work.

The magic is the => which ensures that when geoSuccess() gets called from within getCurrentPosition() this will still point to the current instance of LocalLegislatorsComponent while otherwise it will point to the getCurrentPosition() function or whereever geoSuccess is being called from.

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

Another way of working around would be

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

Upvotes: 2

Related Questions