简体   繁体   中英

Angular 2: Cannot set property 'location' of null

I am still pretty new to Angular 2 and cant get around this problem.

I am trying to get the users current location and safe his coordinates in a variable called "location". When trying to accomplish this I recieve the following error message: 在此处输入图片说明

The code looks like this:

import { Component, AfterViewInit } from '@angular/core';
import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';
import { AgmCoreModule } from 'angular2-google-maps/core';


@Component({
selector: 'app-home',
templateUrl: './app.home.html',
styleUrls: ['./app.home.css']
})
export class HomeAppComponent {
  //restaurants: FirebaseListObservable<any[]>;
  zoom: number = 8;
  lat: number;
  lng: number;
  location: any = {};

  constructor(private af: AngularFire) {
     //this.restaurants = af.database.list('/restaurants');
  }

  ngAfterViewInit() {
     if (navigator.geolocation) {
       navigator.geolocation.getCurrentPosition(this.setPosition);
     }
  }

  setPosition(position) {
     this.location = position.coords;
     console.log(position.coords);
  }

}

When setting propery location to something like:

location.lat = 32;
location.lng = 53;

It is possible to output their values in the constructor, but in the setPosition function its null.

What am I doing wrong....

You can call using arrow function like so:

navigator.geolocation.getCurrentPosition((pos)=>this.setPosition(pos))

or if it does not send a parameter,

navigator.geolocation.getCurrentPosition(()=>this.setPosition())

navigator.geolocation.getCurrentPosition(this.setPosition)

should be

navigator.geolocation.getCurrentPosition(this.setPosition.bind(this))

Your this is not refering to the page inside setPosition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM