Angular 5 个过多的地理位置响应

Angular 5 too many geolocation position responses

我想在 Angular 5 组件中编写,功能是如果我的当前位置发生变化,则每 3 秒获取一次我的当前位置。

我的代码是这样的:

export class WorkComponent implements OnInit {

 constructor(private userService: UserService) {}

 ngOnInit() {
    this.subscribeCurrentPosition();
  }

  subscribeCurrentPosition() {
    if (window.navigator.geolocation) {
      window.navigator.geolocation.watchPosition(
        (position) => {
          this.myLocation = new TrackLocation(null, position.coords.latitude, position.coords.longitude);
          this.userService.sendCurrentPosition(this.myLocation, this.supplierId);  //send position to backend
          setInterval(() => this.subscribeCurrentPosition(), 3000);
        }, (error) => {
          LoggingService.error('Geolocation error: '+ error);
        });
      } else {
        LoggingService.error('Geolocation not supported in this browser');
      }
  }
}

我在函数 subscribeCurrentPosition() 中收到位置更改,但问题是每 3 秒函数被调用的次数越来越多 1、2、4.. 似乎每个函数调用,调用 2 次下一个函数。 然后我收到警报,说我从地理定位 api.

发送了太多请求

我不知道为什么函数 subscribeCurrentPosition() 每 3 秒调用一次以上。 时间组件只有一个实例。

这是因为您正在使用 setInterval。每次使用 setInterval,您都在创建一个将无限期重复的新任务。每次你的函数执行时,你都会递归调用 sentInterval 。这就是为什么您会看到这些任务随着时间的推移而成倍增加。请改用 setTimeout。它只会执行一次。并且由于您使用的是递归机制,因此每次收到响应时都会继续调用它:

  subscribeCurrentPosition() {
    if (window.navigator.geolocation) {
      window.navigator.geolocation.watchPosition(
        (position) => {
          this.myLocation = new TrackLocation(null, position.coords.latitude, position.coords.longitude);
          this.userService.sendCurrentPosition(this.myLocation, this.supplierId);  //send position to backend
          setTimeout(() => this.subscribeCurrentPosition(), 3000);
        }, (error) => {
          LoggingService.error('Geolocation error: '+ error);
        });
      } else {
        LoggingService.error('Geolocation not supported in this browser');
      }
  }

或者,您可以使用 setInterval,但在您的函数之外执行:

  subscribeCurrentPosition() {
    if (window.navigator.geolocation) {
      window.navigator.geolocation.watchPosition(
        (position) => {
          this.myLocation = new TrackLocation(null, position.coords.latitude, position.coords.longitude);
          this.userService.sendCurrentPosition(this.myLocation, this.supplierId);  //send position to backend
        }, (error) => {
          LoggingService.error('Geolocation error: '+ error);
        });
      } else {
        LoggingService.error('Geolocation not supported in this browser');
      }
  }
  setInterval(() => this.subscribeCurrentPosition(), 3000);