【发布时间】:2017-12-14 04:09:10
【问题描述】:
我想在 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 秒调用一次以上。 时间只有一个组件实例。
【问题讨论】:
标签: javascript angular typescript geolocation angular5