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 :
From what I understand you want to do the following:
- enrich each item in the
itemsarray - convert it to a promise
- await this promise
- 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:
lastValueFromis used to convert an observable stream to a promise (and return the last value)forkJoinis used to subscribe to multiple observables and emit the result array after each of them have completedmapis used to "enrich" the initial items