I am trying to implement an Angular 5 component that will continuously fetch my current location every 3 seconds if it has changed. Here is a snippet of my code:
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);
setInterval(() => this.subscribeCurrentPosition(), 3000);
}, (error) => {
LoggingService.error('Geolocation error: '+ error);
});
} else {
LoggingService.error('Geolocation not supported in this browser');
}
}
}
The issue I am facing is that the subscribeCurrentPosition() function is being called multiple times within the 3-second interval, resulting in redundant requests to the geolocation API and eventually triggering an alert for sending too many requests.
I have confirmed that there is only one instance of the component at any given time, so I am unsure why the function is being invoked more than once within the specified timeframe. Any insights or suggestions would be greatly appreciated.