1

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

Lokesh Pandey
  • 1,739
  • 23
  • 50

1 Answers1

2

Because of the way that you bound the getCurrentPosition callback, this does not refer to anything in that callback.

Try using the arrow function so that the current context refers to your component

navigator.geolocation.getCurrentPosition(pos => this.showPosition(pos));
David
  • 33,444
  • 11
  • 80
  • 118