在这里进行了一些研究之后,我发现在Rxjs中进行多个请求的最佳方法是flatMap()。但是,当flatMap()方法中还有多个请求时,我也无法使其工作。 subscription()中的输出是可观察的,而不是值。
this.companyService.getSuggestions(reference)
.pipe(
flatMap((suggestions: string[]) => {
let infos = [];
suggestions.forEach(suggestion => {
infos.push(this.companyService.getInformation(suggestion));
});
return of(infos);
}),
).subscribe((val) => {
console.log('subscribe', val); //Output here is array of observables instead of values
});
答案 0 :(得分:1)
flatMap将仅等待一个值。
我会将建议字符串[]转换为流,并对其进行flatMap。
import { flatMap, from } 'rxjs/operators'
const suggestionsRequest$ = this.companyService.getSuggestions(reference)
// convert to suggestion stream
const suggestions$ = suggestionsRequest$.pipe(
flatMap((suggestions: string[]) => from(suggestions))
)
// get all infos
const infos$ = suggestions$.pipe(
flatMap((suggestion: string) => this.companyService.getInformation(suggestion))
)