Angular 中的重复功能失败

Repeat function failed in 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() 以及为什么会出现错误?

调用间隔的正确方法是使用函数声明 setInterval(this.findMe, 3000);。正如您所指出的,如果您包含 () 它只会执行一次。

setInterval 带来的问题之一是它改变了执行函数的 this 上下文。要解决这个问题,您需要强制它保持不变。

constructor(public globalvar: GlobalvarService) {
  this.findMe = this.findMe.bind(this);
}

附加信息:

您可以只使用保留 this 上下文的箭头函数:

setInterval(() => this.findMe(), 3000);

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

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

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

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

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

尝试

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

但我认为更好的解决方案是使用 Observable 间隔。

interval(3000).subscribe(res => {
   this.findMe()
})

或旧版本的 Angular :)

Observable.interval(3000).subscribe(res => {
   this.findMe()
})