I have a BehaviorSubject
set up as follows:
public _location: BehaviorSubject<Location | undefined> = new BehaviorSubject(undefined);
public location$: Observable<Location | undefined> = this._location.asObservable();
public get location() {
return this._location.getValue();
}
My goal is to access the data like this:
this.location$.subscribe((location) => {
if (typeof location !== 'undefined') {
let coordinates = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
}
});
However, despite my attempts, I keep getting the Typescript error message:
[ts] Object is possibly 'undefined'.
This occurs when trying to access location.coords.latitude
and location.coords.longitude
.
I'm confused. I've specified that the type can be either Location
or undefined
. I've initialized it with undefined
. I've also added a check with typeof location !== 'undefined'
. What am I missing here?