如何从forkJoin返回数据



我是 rxjs 的新手,在使用 forkJoin 时遇到问题。

我有一个角度服务,它向另外两个角度服务询问数据并将组合数据返回给组件。

但是当我在我的角度组件中使用以下代码片段调用该服务时,我没有得到所有数据:

this.timeseriesKpiData = this.timeseriesKpiDataService
.getLatestTimeseriesKpi(this.assetId, this.aspectName, this.variableName,

这是我在服务中调用的方法:

timeseriesKpiDataService.ts:

public getLatestTimeseriesKpi(
assetId: string,
aspectName: string,
variableName: string
): any {
const timeseriesKpiData = {
name: '',
value: 'no value found',
unit: '',
properties: [
{
name: 'Asset',
value: 'Unknown Asset'
}
]
};
// set variableName and aspectName
timeseriesKpiData.name = variableName;
timeseriesKpiData.properties.concat( {
name: 'Aspect',
value: aspectName} );
forkJoin (
// get latest timeseries from another service
this.timeseriesService.getLatestTimeseriesValue(assetId, aspectName)
.pipe(
map((latestTimeseries: Timeseries) => {
return latestTimeseries;
}
)),
// get unit
this.aspectService.getUnit(assetId, aspectName)
.pipe(
map((unit: any) => {
return unit;
})
)).subscribe(([latestTimeseries, unit]) => {
if (latestTimeseries !== undefined) {
// set value
timeseriesKpiData.value = latestTimeseries[timeseriesKpiData.name];
// set unit
timeseriesKpiData.unit = unit;
}
}
});  // end of forkjoin
return timeseriesKpiData; // how to return it?
}

我认为问题是叉接,当我将数据返回到组件时它仍在运行,因此我没有获得所有必需的数据(未设置 timeseriesKpiData.value(。

所以我的问题是,我如何从 forkjoin 返回数据,或者以某种方式等待 forkjoin 结束,然后再将数据返回到我的组件?

你应该返回forkjoin,这样你的代码应该看起来像

public getLatestTimeseriesKpi(
assetId: string,
aspectName: string,
variableName: string
): any {
const timeseriesKpiData = {
name: '',
value: 'no value found',
unit: '',
properties: [
{
name: 'Asset',
value: 'Unknown Asset'
}
]
};
// set variableName and aspectName
timeseriesKpiData.name = variableName;
timeseriesKpiData.properties.concat( {
name: 'Aspect',
value: aspectName} );
return forkJoin (
// get latest timeseries from another service
this.timeseriesService.getLatestTimeseriesValue(assetId, aspectName),
// get unit
this.aspectService.getUnit(assetId, aspectName));  // end of forkjoin
}

然后在您的组件中

this.timeseriesKpiDataService
.getLatestTimeseriesKpi(this.assetId, this.aspectName, this.variableName).subscribe(([latestTimeseries, unit]) => {
if (latestTimeseries !== undefined) {
this.timeseriesKpiData:any ={};
// set value
this.timeseriesKpiData.value = latestTimeseries[timeseriesKpiData.name];
// set unit
this.timeseriesKpiData.unit = unit;
}
}
})

最新更新