Angular 2 : Cannot set property 'location' of null

标签 angular typescript angular2-template

我对 Angular 2 还是很陌生,无法解决这个问题。

我试图获取用户的当前位置并将他的坐标保存在一个名为“location”的变量中。尝试完成此操作时,我收到以下错误消息: enter image description here

代码如下所示:

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);
  }

}

将属性位置设置为如下内容时:

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

可以在构造函数中输出它们的值,但在 setPosition 函数中输出 null。

我做错了什么....

最佳答案

你可以像这样使用箭头函数调用:

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

或者如果它不发送参数,

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

关于 Angular 2 : Cannot set property 'location' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41761709/

相关文章:

ionic-framework - 行为主体和本地存储

Angular Material 7 Multi Select - 设置选定值

angular - 将 ViewEncapsulation.None 设置为每个组件

javascript - 粗箭头中的词法 this 上下文

html - 在 Angular 2 应用程序中读取 JSON 文件

javascript - 无法在 View Angular 6 中显示类属性值

javascript - 如何迭代子对象并将所有非对象值转换为字符串

typescript - 如何简化检查 TypeScript 中是否存在属性?

angular - 不支持调用 Angular2SocialLoginModule 函数调用

angular - if else 在 angular2 模板语法中