![](/img/trans.png)
[英]How to use use async and await to get return value from subscribe API call
[英]How to return data from subscribe using async/await
我正在尝试在订阅下执行功能,但就在完成时。 我有两个组件,一个是从后端接收信息的主要父组件,另一个是从祖父那里获取过滤数据的孙组件。
在服务中,有组件间共享数据的功能,还有一个function来处理数据,按我的需要拆分。
sendDataToMap(dataToMap: []) {
this.send_data.next(dataToMap);
}
reciveDataToMap(): Observable<any>{
return this.send_data.asObservable();
}
getDataToRenderOnMap(dataToMap){
dataToMap.forEach((data) => {
this.routesList.push(data?.mbl_vessels?.path);
const currentPos: number[] = Object.values(data?.mbl_vessels?.currentPosition);
this.pointsToFit.push(currentPos);
const marker: IMarker = {
transportType: data?.quote?.transportationMode,
currentPosition: currentPos
}
this.markersToRender.push(marker);
});
return {
routesList: this.routesList,
pointsToFit: this.pointsToFit,
markersToRender: this.markersToRender
}
}
在父组件中,有过滤具有该属性的数据,并发送数组的过程。
this.elementsToMap = elementsReq.data.filter(item => item.hasOwnProperty('mbl_vessels'));
this.miniMapService.sendDataToMap(this.elementsToMap);
接收数据,处理,并使用一个 function 来获取我需要用于在 map 上绘制路线和其他过程的数据。
ngAfterViewInit() {
this.loadMap(MapStyles.COLOR_STYLE);
this.loadMapControls();
this.prepareDataToMap();
//The idea is to execute the functions below once is finished the subscribe process end
//And return the data out of subscribe
this.setLineStyle(LinePathColor.TO_COLOR, geoData);
this.setCustomMarkers();
this.setMarkerForBounding(shipmentsDataPosition);
this.cdref.detectChanges();
}
prepareDataToMap(){
this.miniMapService.reciveDataToMap().subscribe((data) => {
this.dataToMap = data;
this.dataReturned = this.miniMapService.getDataToRenderOnMap(this.dataToMap);
});
}
setLineStyle(colorPath: string, route?) {
this.mapa.on('load', () => {
this.mapa.addSource('route', {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'LineString',
'coordinates': route
}
}
});
this.mapa.addLayer({
'id': 'route',
'type': 'line',
'source': 'route',
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': colorPath,
'line-width': 2,
"line-dasharray": [0.2, 2]
}
});
});
}
第一个控制台显示未定义,第二个显示数据,但这是因为在订阅内部。
我得到的数据一旦在孙子组件中收到就被处理
如果您想在可观察对象结束时执行某些操作,也许您可以尝试使用完整的可观察对象方法
https://rxjs.dev/guide/observable
当发出完整的值时,您运行这些方法Observables:Complete vs finally vs done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.