我有这个服务,它通过使用对我的 API 的 GET 请求来观察时间间隔的变化:
使用的包: https ://github.com/Asymmetrik/ngx-leaflet
Coords.ts 模型
export class Coords {
constructor(public lat: number,
public lng: number,
public code: string,
public uuid: string) {}
}
地图服务.ts
@Injectable()
export class RealTimeDataService {
constructor(private http: HttpClient) { }
private dataSubject: BehaviorSubject<Coords[]> = new
BehaviorSubject([]);
data$: Observable<Coords[]> = this.dataSubject.asObservable();
updateData(): Observable<any> {
return this.getData().do((data) => {
this.dataSubject.next(data);
});
}
// My data is an array of model objects
getData(): Observable<Coords[]>{
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8', 'code':'0T86MIT'});
return this.http.get(`${AUTH_API_URL}/user/coords`, {headers: headers})
.map((response: Coords[]) => {
let data = response;
if(data){
return data;
}
})
}
}
这是地图组件:
map.component.ts
export class MapComponent implements OnInit, OnDestroy {
constructor(private realTimeDataService: RealTimeDataService, private
zone: NgZone) {
}
LAYER_OSM =
tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{maxZoom: 18, attribution: '© <a
href="http://osm.org/copyright">OpenStreetMap</a> contributors'});
markers: Layer[] = [];
options = {
layers: [this.LAYER_OSM],
zoom : 13,
center: latLng(38.274452, 21.755992)
};
private unsubscribe: Subject<any> = new Subject();
private subscription: Subscription;
data: Coords[];
interval: any;
ngOnInit() {
this.refreshData();
if (this.interval) {
clearInterval(this.interval);
}
this.interval = setInterval(() => {
this.refreshData();
}, 2000);
this.realTimeDataService.data$.takeUntil(this.unsubscribe)
.subscribe(data => {
this.zone.run(() => {
this.data = data;
// this.markers = [];
if (data.length > 0) {
data.map((a, index) => {
let lat = a.lat;
let lng = a.lng;
let uuid = a.uuid;
const newMarker = marker(
[lat, lng],
{
icon: icon({
iconSize : [25, 41],
iconAnchor: [13, 41],
iconUrl : 'assets/marker-icon.png',
shadowUrl : 'assets/marker-shadow.png'
})
}
);
newMarker.bindPopup('<p>' + uuid + '</p>', {autoPan: true});
this.markers.push(newMarker);
});
}
// console.log('sub', data);
});
});
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
refreshData() {
this.realTimeDataService.updateData()
.takeUntil(this.unsubscribe)
.subscribe();
}
}
map.component.html
<div class="map-padding" *ngIf="data.length > 0">
<div style="height: 1000px;"
leaflet
[leafletOptions]="options"
[leafletLayers]="markers">
</div>
</div>
每次data
包含lat,lng
刷新的时候,旧标记都不会被删除。如果我设置this.markers = []
的是一种解决方法,但如果用户单击标记,则弹出窗口将保持打开状态 2 秒(直到新数据出现)。当新数据进入时,我如何保持弹出窗口处于打开状态?
问题预览:(我只是点击了一次,当新数据进来时弹出窗口自动消失)
编辑:
除此之外,如果新数据与旧数据相同,是否有办法告诉 observable 停止/暂停流式传输?