Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to return the value from subscribe?

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
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading