如何使用来自另一个可观察对象的数据更改第一个可观察对象的数据,包括 angular/rxjs 中的条件
how to change the data of the first observable using data from another observable including the condition in angular/rxjs
我 运行 遇到了一个有问题的问题,让我提供一个没有任何业务细节的示意性示例,所以我正在获取一些数据(例如汽车通过 getCars()) 从 API 到 returns 一个 Observable。我需要通过汽车模型从另一个端点获取数据(例如通过 getFeatures(model) 的特征)然后替换特征数据(我们应该为每辆车做)。
除了这个问题,我们如何才能嵌入一个条件运算符来仅在 (model === 'porsche') 时发出对 getFeatures(...) 的请求?
this.getCars().pipe(
map(cars => {
...
}))
.subscribe(cars => {})
export interface Car {
id: string,
model: string,
engine: string,
details: Detail[]
}
export interface Detail {
features: string[]
...
}
你有什么想法可以告诉我吗?这将非常有帮助..提前致谢:)
let cars$ = getCars();
let carsWithFeatures$ = cars$.pipe(
map((cars) =>
cars
.filter((car) => car.model === 'porsche')
.map((car) =>
getFeatures(car.model).pipe(map((features) => ({ ...car, features })))
)
),
mergeMap((cars$) => forkJoin(cars$))
);
- 使用纯 JS 数组过滤器过滤掉所有除了 Porsche
- 使用纯 JS 数组映射为列表中的每辆剩余汽车调用特征服务
- 将特征结果与匹配的汽车结合(我稍微简化了你的模型)
- 使用
mergeMap
和 forkJoin
将项目组合回单个(数组)对象以供 carsWithFeatures$
发射
Stackblitz(检查控制台选项卡):https://stackblitz.com/edit/rxjs-drukvp
我 运行 遇到了一个有问题的问题,让我提供一个没有任何业务细节的示意性示例,所以我正在获取一些数据(例如汽车通过 getCars()) 从 API 到 returns 一个 Observable。我需要通过汽车模型从另一个端点获取数据(例如通过 getFeatures(model) 的特征)然后替换特征数据(我们应该为每辆车做)。
除了这个问题,我们如何才能嵌入一个条件运算符来仅在 (model === 'porsche') 时发出对 getFeatures(...) 的请求?
this.getCars().pipe(
map(cars => {
...
}))
.subscribe(cars => {})
export interface Car {
id: string,
model: string,
engine: string,
details: Detail[]
}
export interface Detail {
features: string[]
...
}
你有什么想法可以告诉我吗?这将非常有帮助..提前致谢:)
let cars$ = getCars();
let carsWithFeatures$ = cars$.pipe(
map((cars) =>
cars
.filter((car) => car.model === 'porsche')
.map((car) =>
getFeatures(car.model).pipe(map((features) => ({ ...car, features })))
)
),
mergeMap((cars$) => forkJoin(cars$))
);
- 使用纯 JS 数组过滤器过滤掉所有除了 Porsche
- 使用纯 JS 数组映射为列表中的每辆剩余汽车调用特征服务
- 将特征结果与匹配的汽车结合(我稍微简化了你的模型)
- 使用
mergeMap
和forkJoin
将项目组合回单个(数组)对象以供carsWithFeatures$
发射
Stackblitz(检查控制台选项卡):https://stackblitz.com/edit/rxjs-drukvp