javascript - Angular中的重复功能失败
问题描述
对于我的 Angular 项目,我生成了一个地理定位组件,并希望重复一个函数findMe()
来显示当前位置。
component.ts中的部分代码如下所示。
...
export class GeolocationComponent implements OnInit{
@ViewChild('gmap') gmapElement: any;
map: google.maps.Map;
isTracking = false;
marker: google.maps.Marker;
constructor(public globalvar: GlobalvarService) { }
ngOnInit() {
var mapProp = {
center: new google.maps.LatLng(-27.542211, 153.1226333),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
setInterval(this.findMe(), 3000);
}
findMe() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
this.showPosition(position);
console.log("find me");
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
showPosition(position) {
this.globalvar.latitude = position.coords.latitude;
this.globalvar.longitude = position.coords.longitude;
let location = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
this.map.panTo(location);
if (!this.marker) {
this.marker = new google.maps.Marker({
position: location,
map: this.map,
title: 'Got you!'
});
}
else {
this.marker.setPosition(location);
}
}
...
在
ngOnInit(),
我用
setInterval(this.findMe(), 3000);
通过检查日志,我看到findMe()
只调用了一次,但没有像我期望的那样重复。
我也试过改变findMe()
==>findMe
setInterval(this.findMe, 3000);
这一次,日志反复出现,但始终报错:
ERROR TypeError: _this.showPosition is not a function
您能否帮助我如何反复调用findMe()
以及为什么会发生错误?
解决方案
您可以使用箭头函数语法使其工作。
ngOnInit() {
setInterval(() => {
this.findMe()
}, 4000);
}
findMe = () => {
console.log('found');
}
箭头函数始终将其作为组件引用。
推荐阅读
- int - 为什么长生不老药指南说在宏定义中使用引用和取消引用
- javascript - How to reformat form submit url that has GET method on the fly
- excel - 将行值从一张表复制到另一张表以获取 Excel 中匹配的记录
- sql - Oracle 滚动 LEAD 计算
- r - devtools install_github 失败
- apache-kafka - 集群中的kafka机器和kafka通信
- java - NestedScrollView 内的 RecyclerView 滚动速度比 RecyclerView 快
- reactjs - 上传到 Firebase 存储执行,但图像返回为黑色方块。尝试了一切
- angular - 角度应用程序的默认空闲超时是多少?
- ios - 将数据保存在核心数据中会迅速覆盖所有记录