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:
- enrich each item in the
items
array - 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:
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 completedmap
is used to "enrich" the initial items