Home > other >  Observable forkJoin never execute pipe
Observable forkJoin never execute pipe

Time:12-17

Im trying to execute and get values from array of observables (each obtained from literalsService) using pipe. Here is the code:

translateLiterals() {
    const literalsToTranslate: string[] = [
    'certificate_title',
    'with_address',
    'hereby',
    'declare',
    'electronic_records',
    'proceeded_to_shipment',
    'return_address',
    'return_address',
    'addressee',
    'message_subject',
  ];
    const newArray: Observable<string>[] = [];
    literalsToTranslate.map(literal => newArray.push(this.literalsService.getValue('Ngwa.Ngwa', literal)));
    this.literalsArray$ = forkJoin([...newArray]).pipe(map((results) => {
      console.log(results);
      return results;
    }));
  }

Of course im subcribed to the pipe in the html side with:

<ng-container *ngIf="literalsArray$ | async"></ng-container>

but the console.log() never prints nothing... anyone knows why?

CodePudding user response:

Probably this.literalsService.getValue('Ngwa.Ngwa', literal); returns string. If that's the case you need transform it to Observable with:

of(this.literalsService.getValue('Ngwa.Ngwa', literal));

Also forkJoin waits for all given streams to be completed, then emits value.

CodePudding user response:

As the users @ShamPooSham and @martin say in the comments, the problem was that the method this.literalsService.getValue ('Ngwa.Ngwa', literals) was observing the changes of the literals and the method forkJoin never started as literals were not completed. I have created a separate method to solve the problem and have added a take to the initial method:

New Method:

translateString(text: string): Observable<string> {
    return this.literalsService.getValue('Ngwa.Ngwa', text).pipe(
      switchMap((translated) => {
        if (!translated.startsWith('N/A')) {
          return of(translated);
        } else {
          return this.literalsService.getValue('Ngwa.Ngwa', text).pipe(
            skip(1), // First event translation comes not translated
            map((secondTryTranslation) => {
              return secondTryTranslation;
            }));
        }
      }),
    );
  }

Correction of the first method:

    translateLiterals() {
    const literalsToTranslate: string[] = [
    'certificate_title',
    'with_address',
    'hereby',
    'declare',
    'electronic_records',
    'proceeded_to_shipment',
    'return_address',
    'return_address',
    'addressee',
    'message_subject',
  ];
    const newArray: Observable<string>[] = [];
    literalsToTranslate.map(literal => newArray.push(this.translateString(literal).pipe(take(1)))); //<--- Here is the correction
    this.literalsArray$ = forkJoin([...newArray]).pipe(map((results) => {
      return results;
    }));
  }```
  • Related