首页 > 解决方案 > 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()以及为什么会发生错误?

标签: javascriptangulartypescriptrepeat

解决方案


您可以使用箭头函数语法使其工作。

ngOnInit() {
    setInterval(() => {
        this.findMe()
    }, 4000);
}

findMe = () => {
    console.log('found');
}

箭头函数始终将其作为组件引用。

示例 - https://stackblitz.com/edit/angular-wkv2he


推荐阅读