kev*_*evj 1 typescript angular2-template angular
我对 Angular 2 还是很陌生,无法解决这个问题。
我正在尝试获取用户当前位置并将其坐标保存在名为“location”的变量中。尝试完成此操作时,我收到以下错误消息:

代码如下所示:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
将属性位置设置为以下内容时:
location.lat = 32;
location.lng = 53;
Run Code Online (Sandbox Code Playgroud)
可以在构造函数中输出它们的值,但在 setPosition 函数中它的值为 null。
我究竟做错了什么....
您可以像这样使用箭头函数调用:
navigator.geolocation.getCurrentPosition((pos)=>this.setPosition(pos))
Run Code Online (Sandbox Code Playgroud)
或者如果它不发送参数,
navigator.geolocation.getCurrentPosition(()=>this.setPosition())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2713 次 |
| 最近记录: |