javascript - 如何在 Angular 应用程序中订阅 setInterval()?
问题描述
我正在尝试使用 Ionic 5 框架、Angular 和 Cordova 地理定位插件构建一个 iOS 位置跟踪应用程序。
我曾经使用 watchPosition() 函数来获取用户位置更改,并且它在 Android 设备上运行良好。但是,它不适用于 iOS 设备。
我的新方法是使用 getCurrentPosition() 函数结合 setInterval() 来获取当前位置。每隔一两秒获取一次更新的位置。
不幸的是,我现在收到以下错误:
TypeError:this.watchLocationUpdates.subscribe 不是函数
任何人都知道如何解决这个问题?
watchLocation() {
const options = {
maximumAge: 3600000,
timeout: 5000,
enableHighAccuracy: true,
};
this.isWatching = true;
this.trackingId = '-' + Math.random().toString(36).substr(2, 28);
// Please find relevant setInterval() part below
this.watchLocationUpdates = setInterval(() => { this.geolocation.getCurrentPosition(options); }, 1000);
this.watchLocationUpdatesSub = this.watchLocationUpdates.subscribe((resp) => {
this.geoLocations = resp.coords;
this.geoLatitude = resp.coords.latitude;
this.geoLongitude = resp.coords.longitude;
this.geoAccuracy = Math.trunc(resp.coords.accuracy);
this.timeStamp = resp.timestamp;
const position = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
this.map.setCenter(position);
this.map.setZoom(16);
this.markers.map(marker => marker.setMap(null));
this.markers = [];
const latLng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
const marker = new google.maps.Marker({
map: this.map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 13,
fillColor: '#1AA0EC',
fillOpacity: 1,
strokeColor: 'white',
strokeWeight: 2
},
position: latLng
});
this.markers.push(marker);
console.table('watchLocation function called', {
trackingId: this.trackingId,
latitude: this.geoLatitude,
longitude: this.geoLongitude,
accuracy: this.geoAccuracy,
timeStamp: this.timeStamp,
uId: this.uId
});
this.geolocationService.insertUserGeolocation({
trackingId: this.trackingId,
latitude: this.geoLatitude,
longitude: this.geoLongitude,
accuracy: this.geoAccuracy,
timeStamp: this.timeStamp,
uId: this.uId
})
.subscribe((response) => {
localStorage.setItem('lastLocation', JSON.stringify({
trackingId: this.trackingId,
latitude: this.geoLatitude,
longitude: this.geoLongitude,
accuracy: this.geoAccuracy,
timeStamp: this.timeStamp,
uId: this.uId
}));
console.log(`user location data inserted in FB`, {
trackingId: this.trackingId,
latitude: this.geoLatitude,
longitude: this.geoLongitude,
accuracy: this.geoAccuracy,
timeStamp: this.timeStamp,
uId: this.uId
});
});
});
}```
解决方案
您可以使用interval()
来自 RxJS的:
// RxJS v6+
import { interval } from 'rxjs';
const source = interval(1000);
source.subscribe(/* your logic here */);
推荐阅读
- php - 如何从mysql数据库表中仅获取php数组的匹配项
- http - 如何在 G-WAN 中添加 HTTP/2
- php - 根据 woocommerce 中的一系列尺寸(面积)设置产品价格
- c# - 验证数据模型
- angular - 构建 Angular 应用程序并放在服务器上
- c# - 如何针对“从查询到输出快捷方式”优化此方法
- c# - Unity3d将刚体添加到MenuItem中的对象
- c# - 自定义 ClickOnce 安装路径
- react-native-android - 是否可以使用离线 pc 为 android 编译一个 react-native 应用程序
- php - 删除最后一个标点符号形式的 wordpress 类别列表