我有一个使用一些自定义组件的 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('""', '""')] = 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('""', '""')] = 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('""', '""')] = 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('""', '""')] = 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/