Home > Net >  Is it possible to return the value from subscribe?
Is it possible to return the value from subscribe?

Time:11-09

this is my translate function, i require to return the array. Is it possible to return from Subscribe - ?

translator(items) {
        const output = items?.map((item) => {
            return this.translate.get(item.label).subscribe((value) => {
                item = { ...item, label: value };
                return item;
            });
        });
        console.log('output', output);//no data
    }

CodePudding user response:

From what I understand you want to do the following:

  1. enrich each item in the items array
  2. convert it to a promise
  3. await this promise
  4. print the output of this promise

You can use the following code in order to achive this:

async translator(items) {
    const output = await lastValueFrom(
      forkJoin(
        items?.map((item) =>
          this.translate
            .get(item.label)
            .pipe(map((value) => ({ ...item, label: value })))
        )
      )
    );

    console.log('output', output); //no data
  }

Explanation:

  • lastValueFrom is used to convert an observable stream to a promise (and return the last value)
  • forkJoin is used to subscribe to multiple observables and emit the result array after each of them have completed
  • map is used to "enrich" the initial items
  • Related