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

标签 angular observable

我有一个使用一些自定义组件的 Angular Reactive 表单。它有一些基本的表单字段以及 Froala 编辑器。我使用自定义下拉菜单自定义编辑器,这些下拉菜单通过可观察的方式从后端获取值。这就是我的问题开始的地方。 我有一个名为 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;
    }
  })
}

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

最佳答案

我认为你应该能够使用 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$);
}

然后在某处:

this.transformArr().subscribe(
  ([contactFieldsOption, personalFieldsOption]) => this.initializeEditor()
)

我还没有测试过这个。但看不出它不起作用的原因。

如果没有,请告诉我。

希望有帮助:)

关于angular - 如何确保在 2 个或更多 Observable 返回数据之前不会执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59276743/

相关文章:

回调中更新的 Angular 变化检测

javascript - 如何在 Angular 10 中修补动态表单数组的值?

javascript - 导入自定义模块时获取 'Cannot read property ' ɵmod' of undefined'

angular - 如何停止 IntervalObservable

javascript - 等待可观察完成

angular - 如何在 Angular 中刷新组件

javascript - Angular 服务中的 EventEmitter 是好是坏?

javascript - Observable 完成后返回单个对象

swift - RXSwift如何结合最新使用,看起来像什么,闭包中的匿名类并处理附加参数

Angular 2 Renderer2 prependChild-like 行为