Rxjs 可观察流,其值从其他流中丰富而来;“一枪”;可观测

Rxjs 可观察流,其值从其他流中丰富而来;“一枪”;可观测,rxjs,observable,rxjs-pipeable-operators,Rxjs,Observable,Rxjs Pipeable Operators,我有一个helper函数,它进行API调用并返回一个项数组。这些项中的每一项都代表一个实体,比如说一个用户 每个用户都有一个默认为空的category\u id属性。我想从另一个helper函数的结果中为每个用户填充此属性,该函数获取用户ID并返回类别对象的可观察值,我可以从中提取ID,用作用户的Category\u ID属性 我已经了解了以下(伪)代码(TypeScript语法,但这个问题通常适用于可观察运算符): 当然,这不起作用,因为它将可观测操作符与数组函数(forEach)混合在一起。

我有一个helper函数,它进行API调用并返回一个
项数组
。这些项中的每一项都代表一个实体,比如说一个
用户

每个用户都有一个默认为空的
category\u id
属性。我想从另一个helper函数的结果中为每个用户填充此属性,该函数获取用户ID并返回类别对象的可观察值,我可以从中提取ID,用作用户的
Category\u ID
属性

我已经了解了以下(伪)代码(TypeScript语法,但这个问题通常适用于可观察运算符):


当然,这不起作用,因为它将可观测操作符与数组函数(forEach)混合在一起。

您不应该将其复制到管道中的可观测操作符。这是一种反模式。 使用更高的可观察和合并地图与CombineTest,以获得您想要的:

this.backend
.request(
  'v1/users',
)
.pipe(
  mergeMap(items => {
    const requestUserWithCatArray = items.map(user => this.categories.getName(user['id']).pipe(
        map(category => {
             user['category_id'] = category['id'];
             return user;
        })
    ));
    return combineLatest(requestUserWithCatArray);
  })
);

它将返回一个包含用户类别的数组。

您可以使用
forkJoin
而不是
combinelatetest
并行运行请求,而不是按顺序运行请求(假定
this.categories.getName(user['id'))
completes)。在这种情况下,forkJoin可能会更好地使用,是的。
this.backend
.request(
  'v1/users',
)
.pipe(
  mergeMap(items => {
    const requestUserWithCatArray = items.map(user => this.categories.getName(user['id']).pipe(
        map(category => {
             user['category_id'] = category['id'];
             return user;
        })
    ));
    return combineLatest(requestUserWithCatArray);
  })
);