如何确保在 2 个或更多 Observable 返回数据之前不执行函数?

Mis*_*Guy 2 observable angular

我有一个使用一些自定义组件的 Angular Reactive 表单。它有一些基本的表单字段以及一个 Froala 编辑器。我使用自定义下拉列表自定义编辑器,这些下拉列表通过 observable 从后端获取值。这是我的问题开始的地方。我有一个名为的函数transformArr(),它看起来像这样

transformArr() {
  console.log('Transform Contact Options')
  this.contactFields$ = this.mailTemplateService
    .templateLookup(this.guids.MAIL_TEMPLATE_CONTACT_FIELDS);
  this.contactFields$.subscribe(res => {
    this.contactFieldsOption = new Object() as {
      [key: string]: string
    };

    for (const each of res) {
      this.contactFieldsOption[each.value.replace('""', '&#34&#34')] = each.name;
    }
  })

  console.log('Transform Personal Options')
  this.personalFields$ = this.mailTemplateService
    .templateLookup(this.guids.MAIL_TEMPLATE_CONTACT_FIELDS);
  this.personalFields$.subscribe(res => {
    this.personalFieldsOption = new Object() as {
      [key: string]: string
    };

    for (const each of res) {
      this.personalFieldsOption[each.value.replace('""', '&#34&#34')] = each.name;
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

只有当两者都完成时我才想运行 this.initializeEditor();

Sid*_*era 5

我认为您应该能够使用forkJoin.

在这里,试试这个:

transformArr() {

  console.log('Transform Contact Options');

  this.contactFieldsOption$ = this.mailTemplateService
    .templateLookup(this.guids.MAIL_TEMPLATE_CONTACT_FIELDS)
    .pipe(map(res => {
      this.contactFieldsOption = new Object() as {
        [key: string]: string
      };

      for (const each of res) {
        this.contactFieldsOption[each.value.replace('""', '&#34&#34')] = each.name;
      }
      return this.contactFieldsOption;
    }));

  console.log('Transform Personal Options');

  this.personalFieldsOption$ = this.mailTemplateService
    .templateLookup(this.guids.MAIL_TEMPLATE_CONTACT_FIELDS)
    .pipe(map(res => {
      this.personalFieldsOption = new Object() as {
        [key: string]: string
      };

      for (const each of res) {
        this.personalFieldsOption[each.value.replace('""', '&#34&#34')] = each.name;
      }
      return this.personalFieldsOption;
    }));

  return forkJoin(this.contactFieldsOption$, this.personalFieldsOption$);
}
Run Code Online (Sandbox Code Playgroud)

然后在某个地方:

this.transformArr().subscribe(
  ([contactFieldsOption, personalFieldsOption]) => this.initializeEditor()
)
Run Code Online (Sandbox Code Playgroud)

我没有测试过这个。但没有看到它不应该工作的原因。

如果没有,请告诉我。

希望能帮助到你 :)