我想在 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);
关于javascript - Angular 5 太多地理位置响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47801286/