我有 2 个可观察对象:
country$!: Observable<Country>
countryBorders$!: Observable<Country[]>
我尝试从 HTTP GET 请求中检索“country$”数据(在本示例中,国家/地区是美国):
https://restcountries.com/v3.1/name/usa
在检索特定国家/地区数据后,我想将该数据中的“borders”属性数组存储到“countryBorders$”可观察对象中。
现在我正在这样做:
getCountriesByCodes(codes: string[]) {
return this.http.get<Country[]>(
`${this.api}alpha?codes=${codes.join(',')}`
);
}
ngOnInit(): void {
this.activatedRoute.params.subscribe((params) => {
let countryName = params['country'];
this.country$ = this.apiService.getCountryByName(countryName).pipe(map(([info])=>{
this.countryBorders$ = this.apiService.getCountriesByCodes(info.borders);
return info;
}))
});
};
但我被告知你不应该在另一个 Observable 的订阅函数中创建或存储 Observable 值。
我应该在这里使用什么?合并 map ?切换 map ?连接映射?我是否只需将“ map ”替换为其中之一?有人能指出我正确的方向吗?
最佳答案
确实不建议嵌套可观察值。您可以简单地使用 mergeMap
进行更新:
ngOnInit(): void {
this.activatedRoute.params.pipe(
mergeMap((params) => {
let countryName = params['country'];
return this.apiService.getCountryByName(countryName).pipe(
tap(([info]) => {
this.countryBorders$ = this.apiService.getCountriesByCodes(info.borders);
})
);
})
).subscribe(([info]) => {
this.country$ = of(info);
});
}
关于javascript - 如何创建一个 Observable 并同时将该 Observable 中的值存储到另一个 Observable 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74932768/