Angular/RxJS: 超过6个参数的forkjoin

Angular/RxJS: forkjoin with more than 6 parameters

我在加载页面之前使用 forkjoin 来初始化数据。不幸的是,我已经达到 forkjoin 的 6 个参数的限制:

export class Sample implements OnInit {

  list1?: Pair[];
  list2?: Pair[];
  list3?: Pair[];
  list4?: Pair[];
  list5?: PairExt[];
  list6?: PairExt[];
  list7?: PairExt[];

  constructor(private http: HttpService,
              private httpWithCaching: HttpWithCachingService) {
  }

  ngOnInit(): void {
    this.initLists().subscribe(([list1, list2, list3, list4, list5, list6, list7]) => {
      this.list1 = list1;
      this.list2 = list2;
      this.list3 = list3;
      this.list4 = list4;
      this.list5 = list5;
      this.list6 = list6;
      this.list7 = list7;

      this.initModule();
    });
  }

  initLists(): Observable<[Pair[], Pair[], Pair[], Pair[], PairExt[], PairExt[], PairExt[]]> {
    return forkJoin([
      this.httpWithCaching.getList1(),
      this.httpWithCaching.getList2(),
      this.httpWithCaching.getList3(),
      this.httpWithCaching.getList4(),
      this.httpWithCaching.getList5(),
      this.httpWithCaching.getList6(),
      this.httpWithCaching.getList7()
    ]);
  }

  initModule(): void {
     //some requests and initialization after the lists were fetched...
  }

上面的代码将因此不再有效,因为 forkjoin 被限制为 6 个参数。

对于我的情况,最简单的解决方案是什么?我真正想做的就是在调用 initModule...

之前获取列表

提前致谢!

也许回退到传统方法,即 Promises。使用 Promise.all 进行并行 API 调用(类似于 forkJoin)。鉴于在 forkJoin 中 return 一个 Observable 嵌套在 API 调用 complete 之上,我们可以很容易地用 Promise.all

替换它

initLists(): Promise<[Pair[], Pair[], Pair[], Pair[], PairExt[], PairExt[], PairExt[]]> {
   const promises = [this.httpWithCaching.getList1(),
      this.httpWithCaching.getList2(),
      this.httpWithCaching.getList3(),
      this.httpWithCaching.getList4(),
      this.httpWithCaching.getList5(),
      this.httpWithCaching.getList6(),
      this.httpWithCaching.getList7()];

   return Promise.all(promises);
}

注意:未测试

尝试在下面对 forkJoins 进行分组

   return forkJoin([
    forkJoin([
      this.httpWithCaching.getList1(),
      this.httpWithCaching.getList2(),
      this.httpWithCaching.getList3(),
      this.httpWithCaching.getList4(),
      this.httpWithCaching.getList5(),
      this.httpWithCaching.getList6(),
    ]),
    forkJoin([
       this.httpWithCaching.getList7(),
       this.httpWithCaching.getList8(),
    ])

 ]).pipe(
     map( x => x.flat())
  );

映射对于将数据转换回一维数组很有用

换一种方式:

  initLists(): Observable<[Pair[], Pair[], Pair[], Pair[], PairExt[], PairExt[], PairExt[]]> {
    return from([
      this.httpWithCaching.getList1(),
      this.httpWithCaching.getList2(),
      this.httpWithCaching.getList3(),
      this.httpWithCaching.getList4(),
      this.httpWithCaching.getList5(),
      this.httpWithCaching.getList6(),
      this.httpWithCaching.getList7()
    ]).pipe(combineLatestAll());
  }

就是这样!