Home > Net >  Waiting for a method in a loop in effects angular
Waiting for a method in a loop in effects angular

Time:02-12

How can I wait for the loop to finish and get the data? Thought about the forkJoin method, but without success...

    getEntities$ = createEffect(() =>
    this.actions$.pipe(
      ofType(GetEntities),
      mergeMap((s: any) =>
        // first request
        this.service.getEntities(s.id).pipe(
          map((data: Entitites[]) => {
            const entities = cloneDeep(data);
            for (const entity of entities) {
              // second request
              this.service.getAdditionalInfo(s.id, entity.id).subscribe((info: Info) => {
                entity.info = info;
              })
            }
            // getting the old data without additional info
            return entities;
          }),
          mergeMap((entities: Entities[]) => [GetEntitiesSuccess({ entities})]),
          ....

CodePudding user response:

You can achieve that using concat or forkJoin like the following:

getEntities$ = createEffect(() =>
    this.actions$.pipe(
        ofType(GetEntities),
        mergeMap((s: any) => this.service.getEntities(s.id)),
        mergeMap((data: Entitites[]) => {
            const entities = cloneDeep(data);
            return concat(
                ...entities.map((entity) => 
                    this.service.getAdditionalInfo(s.id, entity.id).pipe(map(info: Info) => {
                        entity.info = info;
                        return entity;
                    })
                )
            );
        }),
        mergeMap((entities: Entities[]) => [GetEntitiesSuccess({ entities })])
    )
);
  • Related