javascript - 内部订阅的Angular 6等待方法

标签 javascript angular typescript http asynchronous

我必须通过 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
    })
}

内部组件服务:

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); 
            });
}

你能帮帮我吗?谢谢

最佳答案

您可以使用 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
    })
}

关于javascript - 内部订阅的Angular 6等待方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58218157/

相关文章:

javascript - this.props 上的属性不存在

javascript - 使用 angularjs+codeigniter 成功添加用户时在 html 中显示消息

angular - Angular 中的单元测试 : Mocking RxJS observable with Jasmine

javascript - 在 Angular4(typescript) 中实现 zimJS

typescript - 如何在 Angular 2 中处理纯文本、服务器响应?

javascript - Angular - 将两个 observables 组合在一个 ngIf 中

azure - 从GitHub部署TypeScript WebSite到Azure

javascript - 删除下拉列表中的垂直滚动条

javascript - Onclick JS函数识别元素Onclick

javascript - 切换具有多个值的选择器 CSS