I have gone through different threads on SO regarding null service. But I didn't get my answers. What I am trying to do is when my component is being loaded, I am trying to get the user's current location.
export class MainComponent implements OnInit {
constructor(private userLocation: UserLocationService) {}
ngOnInit(){
this.getLocation()
}
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
showPosition(position) {
console.log(position.coords.latitude + " " + position.coords.longitude)
let userCordinates = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
this.userLocation.setCurrentUserLocation(userCordinates)
}
}
Once I get the coordinates, I am trying to set the coodinates in a service, so that I can get it from another component. This is the service
import { Injectable } from '@angular/core';
import { UserLocationInterface } from './user.location.interface'
@Injectable({
providedIn: 'root'
})
export class UserLocationService {
constructor() { }
userLocation: UserLocationInterface
getCurrentUserLocation() {
return this.userLocation;
}
setCurrentUserLocation(userLocationCords) {
this.userLocation = userLocationCords;
}
}
I have mentioned the service in app.module in providers container. I can see the coordinates in console logs. But when my main component is being loaded, I can see this error
ERROR TypeError: Cannot read property 'userLocation' of null
This userLocation
is throwing this error in main component. I didn't get here what's wrong. Is my service null ? Or am I missing something ?
Thanks