如何合并两个可观测结果流
Angular服务方法:
getDetails<T>(date: string) Observable<typeA<T>> {
return this.myService.getMyDetails(date);
}
getFullYearDetails(id: number, year: number): Observable(typeB>{
return this.myService.getYearData(id, year);
}
第一种方法返回:
{ records [
{ id: 28, somemoredata: [{a: 123, b: 12345}], totalOfSomething: 2000 },
{ id: 32, somemoredata: [{a: 345, b: 26435}], totalOfSomething: 3000 }
]}
第二种方法的结果:
{
id: 28,
year: 2026,
months: [
{id: 1, total: 1000]},
{id: 2, total: 1500]}
}
如果我调用getDetails,我想得到期望的结果/相同的结果,但总额必须来自特定月份的数据。(示例:id: 28,月份: 2)
{id: 28, somemoredata: [{a: 123, b: 12345}], totalOfsomething: 1500}
我修改了我的代码为(我使用date-fns,日期输入为 '02-2026'):
getDetails<T>(date: string) Observable<typeA<T>> {
const month = getMonth(parse(date, 'MM-yyyy', new date())); // result 1
const month = getYear(parse(date, 'MM-yyyy', new date())); // result 2026
this.myService.getMydetails(date).pipe(
switchMap(details =>({
return this.myService.getFullYearDetails(details.records[0].id, year).pipe(
map(yeardata => ({
...details,
})
)
})
)
// return this.myService.getMyDetails(date);
}
服务方法getdetails是从另外一个文件中的组件调用的,且期望得到一个observable对象。
我添加了 records[0].totalOfsomething : yeardata.months[1].total,但这不起作用。
我该如何返回所期望的结果?
解决方案
我们可以用 from 把记录数组转换成一个observable流。随后我们使用 concatMap 逐步获取年度数据总和,使用 tap 将内部observable的目标值赋给记录数组对象。接着用 last 运算符让流等待直到最后一个元素被处理。最后我们用 map 返回附加数据的原始详情。
getDetails<T>(date: string) Observable<typeA<T>> {
const month = getMonth(parse(date, 'MM-yyyy', new date())); // result 1
const month = getYear(parse(date, 'MM-yyyy', new date())); // result 2026
this.myService.getMydetails(date).pipe(
switchMap(details => {
return from(details.records).pipe(
concatMap((record: any) => {
return this.myService.getFullYearDetails(record.id, year).pipe(
tap((yeardata) => {
record.totalOfsomething = yeardata?.months?.find(x=>x.id==month)?.total;
})
);
}),
last(),
map(() => details),
)
})
);
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。