如何合并循环订阅数据angular 2 TS

时间:2017-09-20 11:20:54

标签: angular angular2-observables

fieldRender(formSets: any[]) {

    let questions: any[] = [];
    let q: QuestionBase<any>[] = [];
    let index: number = 0;

    formSets.forEach(formSet => {
      formSet.children.forEach(child => {
        this.appointmentService.getField(child.field.uuid).subscribe(res => {
          let dataType;
          let label;
          let parent;
          let uuid;
          let answers = [];

          if (res.concept != null) {
            if (res.concept.datatype)
              dataType = res.concept.datatype.display;
            if (res.answers)
              answers = res.answers;
          }
          uuid = res.uuid;
          label = res.display;
          parent = formSet.parent.field.display;

          let question: Question = new Question();
          question.label = label;
          question.type = dataType;
          question.parent = parent;
          question.uuid = uuid;
          question.answers = answers;

          questions.push(question);

          console.log("Questions", JSON.stringify(questions));
        });
      });
    });

  }

这是我的函数。我希望这个函数返回Observable of Questions,我可以订阅它以获取数据。 FormSet是一个FormSet数组 FormSet包含父项和子数组

1 个答案:

答案 0 :(得分:0)

如果formSet.children是一个数组,您可以执行与thi

类似的操作
Rx.Observable.from(formSet.children)
.flatMap((child) => this.appointmentService.getField(child.field.uuid))
.subscribe((question) => questions.push(question))

通过这种方式,您可以将getField的所有响应放在一个&#34; stream&#34;

你没有给我们太多的背景,所以我猜测;)