如何执行顺序服务呼叫?

时间:2019-09-19 13:18:37

标签: angular rxjs

我需要调用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;             
            });
          });
      });

第二个订阅从未达到。

1 个答案:

答案 0 :(得分:1)

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

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 });

(我的括号内的数字很有可能是错误的)。