-2

This is my translation method. getting empty array on console. how to handle this?

 headersTranslator(headers) {
    const transHeader: any[] = [];
    headers.map((header) => {
        this.translate.get(header.title).subscribe((value) => {
            if (!value) return;
            transHeader.push({ ...header, title: value });
        });
    });
    console.log('transHeader', transHeader);
    return transHeader;
}

my try: finding challenging because of observable placed under the loop.

 headersTranslator(headers) {
    const transHeader: any[] = [];
    return new Promise((resolve, reject) => {
        headers.map((header) => {
            this.translate.get(header.title).subscribe({
                next: (value) =>
                    transHeader.push({ ...header, title: value }),
            });
        });
        resolve(transHeader);
    });
}
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247
  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Dec 06 '22 at 12:16
  • @R.Richards - can you check my update? – 3gwebtrain Dec 06 '22 at 12:42

2 Answers2

1

You need to use some operator like forkJoin to convert an array of observables to a single observable that returns an array of results of those underlying observables

For async version use firstValueFrom or lastValueFrom:

async function headersTranslator(headers) {
    const observables = headers.map(header =>
                                    this.translate.get(header.title)
                                    .pipe(map(value => ({ ...header, title: value }))));
    return await lastValueFrom(forkJoin(observables));       
}

Or if you want the function to return the observable and subscribe to it:

function headersTranslator(headers) {
    const observables = headers.map(header =>
                                    this.translate.get(header.title)
                                    .pipe(map(value => ({ ...header, title: value }))));
    return forkJoin(observables);       
}
theemee
  • 769
  • 2
  • 10
0

I tried this, it works.

async headersTranslator(headers) {
    const transHeader: any[] = [];
    return new Promise((resolve, reject) => {
        headers.map((header, i) => {
            this.translate
                .get(header.title)
                .subscribe({
                    next: (value) =>
                        transHeader.push({ ...header, title: value }),
                })
                .add(() => {
                    if (headers.length === i + 1) {
                        resolve(transHeader);
                    }
                });
        });
    });
}

But looking for a standard way to get it.

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247