我必须通过forEach多次调用服务,该方法内部具有订阅(http调用)的功能,并且每次都必须等待上一次调用的结束。 这是代码:
itemDefaultConfiguration.command = (onclick) => {
this.createConfiguration(configuration.components);
//wait the end of createConfiguration method that has subscribe (http call) inside
this.initializeAllComponents(configuration.components)
};
initializeAllComponents(components: Agent[]) {
components.forEach(agent => {
this.componentService.setAgent(agent);
this.componentService.clearAnyOneOfIndex();
// wait the end of setAgent method that has subscribe(http call) inside
})
}
内部componentService:
setAgent(agent: Agent) {
this.agent = agent;
this.selectComponent(agent.name, undefined, "/", "/", environment.maxLevelJsonSchema);
}
和selectComponent具有订阅。
selectComponent(agentName: string, propName: string, schemaPath: string, dataPath: string, deepLevel: number) {
this.getComponentSchema(this.agentName, schemaPath, deepLevel)
.subscribe((responseSchema) => {
this.getDataFailure(propName, dataPath, responseSchema);
});
}
你能帮我吗?谢谢
答案 0 :(得分:0)
您可以使用await来做到这一点,例如:
initializeAllComponents(components: Agent[]) {
components.forEach(async agent => {
await this.componentService.setAgent(agent).catch(console.log);
this.componentService.clearAnyOneOfIndex();
// wait the end of setAgent method that has subscribe(http call) inside
})
}
答案 1 :(得分:0)
您可以使用async/await语法来实现:
initializeAllComponents(components: Agent[]) {
for (let i = 0; i < components.length; i++) {
const agent = components[i];
await this.componentService.setAgent(agent).catch(console.log);
this.componentService.clearAnyOneOfIndex();
}
}
请注意async/await
,因为您需要使用本机for
循环才能等待上一个调用-forEach
,reduce
和类似方法只会触发多个异步电话。
答案 2 :(得分:0)
如果是param_b
,请尝试使用Observable
运算符:
switchMap
如果不是import { switchMap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
initializeAllComponents(components: Agent[]) {
components.forEach(agent => {
this.componentService.setAgent(agent).pipe(
switchMap(res => {
if (res) { return this.userService.get(user.uid); }
return of(null);
}));
);
this.componentService.clearAnyOneOfIndex();
})
}
,则使用Observable
运算符:
async/await