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
- The JSON is well received and I can print it, also its subobjects. I can even bind it to a local variable within the setValues method. I also tried binding that local variable to the properties but that caused the same error.
- Changing
lat: any
tolat: number
or addingpublic
in front of it. - Getting rid of the null operators in the setValues method.
- Putting the code in the ngOnInit method.
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).