我想用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秒调用一次以上。 只有一个组件实例及时。
答案 0 :(得分: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);