Introduction
I'm working on an Angular application where I want to get the current position of the user and save the longtitude and altitude in two properties lng
and lat
, yet this doesn't seem to work and no matter what I try; I keep on getting the error ERROR TypeError: Cannot set property 'lat' of null
TypeScript code (the relevant part)
lat : any;
lng : any;
constructor() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.setValues);
}
}
setValues(values) {
this.lat = values?.coords?.latitude
this.lng = values?.coords?.longitude;
}
The error is thrown in the first line of setValues
The (relevant part of the) JSON object that is returned by getCurrentPosition
{
coords:
{
latitude: 27.380583,
longitude: 33.631839
}
}
What I tried
lat: any
to lat: number
or adding public
in front of it.All of these tries caused the same error.
The problem is to do with what this
refers to in different scopes. It only refers to the outer scope (the component in this case) when you use an arrow function. Otherwise this
refers to the funtion itself.
You can see it in action for yourself by setting up the following test:
ngOnInit() {
// 1. delegate function
this.getValues(this.setValues);
// 2. function() { }
this.getValues(function(values) {
console.log(this);
});
// 3. arrow function
this.getValues(values => this.setValues(values));
}
getValues(callback: (values) => void) {
callback({
lat: 1,
long: 2
});
}
setValues(values) {
console.log(this);
}
This shows 3 different ways of passing a function in as a callback. 1. and 2. will log undefined
to the console. 3. will log the containing class (AppComponent
in my demo).