如何执行顺序服务呼叫?



我需要调用 2 个服务,第二个服务需要使用第一个服务检索到的数据调用。 第一个服务返回一个包含类别 ID 的对象数组,对于每个 ID,我需要使用第二个服务来获取与所述 ID 关联的项目。 问题是,当使用"项目"服务时,订阅似乎不起作用。

我已经尝试在第一个调用中嵌套第二个调用,以便合并 Observable,但没有任何结果。

categoriesArray: Category[];
categoryItemsArray: [CategoryItem[]];
this.firstService
.query({ 'sectionId.equals': this.section.id })
.pipe(
filter((res: HttpResponse<Category[]>) => res.ok),
map((res: HttpResponse<Category[]>) => res.body))
.subscribe(
categories => {
this.categoriesArray = categories;
},
error => console.error(error),
() => {
this.categoriesArray.forEach(( category, index) => {
console.log('entered ForEach loop');
this.secondService.query({ 'categoryId.equals': category.id })
.pipe(
filter((res: HttpResponse<CategoryItem[]>) => res.ok),
map((res: HttpResponse<CategoryItem[]>) => res.body))
.subscribe( (categoryItems, index) => {
console.log('second subscribe');
this.categoryItemsArray[index] = categoryItems;             
});
});
});

永远不会到达第二个订阅。

不要在订阅中订阅。开始之后:

this.firstService
.query({ 'sectionId.equals': this.section.id })
.pipe(
filter((res: HttpResponse<Category[]>) => res.ok),
map((res: HttpResponse<Category[]>) => res.body),

我们切换到另一个流,switchMap运算符如下所示:

switchMap(categories => forkJoin(
categories.map(this.requestSingleCategory)
))

这里同时发送n 个请求。剩下的就是订阅和使用结果:

).subscribe((categoryItems) => this.categoryItemsArray = categoryItems);

为了可读性,我将requestSingleCategory重构为单独的函数:

private requestSingleCategory = ({ id }) => this.secondService.query({ 'categoryId.equals': id });

(我的括号计数很有可能是错误的(。

最新更新