Угловой 6 метод ожидания с подпиской внутри - PullRequest
1 голос
/ 03 октября 2019

Мне приходится вызывать службу несколько раз, для 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); 
            });
}

Можете ли вы мне помочь? Спасибо

Ответы [ 3 ]

0 голосов
/ 03 октября 2019

Вы можете добиться этого, используя 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 для ожидания предыдущегоcall - forEach, reduce и подобные методы просто запускают несколько асинхронных вызовов.

0 голосов
/ 03 октября 2019

Если это 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:

async initializeAllComponents(components: Agent[]) {
    components.forEach(agent => {
      let result = await this.componentService.setAgent(agent);
      this.componentService.clearAnyOneOfIndex();
      // wait the end of setAgent method that has subscribe(http call) inside
    })
}
0 голосов
/ 03 октября 2019

Вы можете сделать это, используя 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
    })
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...