Within my code, there exists an observable array filled with objects:
let people = of([
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Jane', lastName: 'Doe' },
{ firstName: 'John', lastName: 'Smith' },
{ firstName: 'Jane', lastName: 'Smith' },
])
In addition, a function is present that leverages two properties from the objects to generate an observable:
function fullName(firstName: string, lastName: string) {
return of(`${firstName} ${lastName}`)
}
The challenge I am facing involves combining these two elements to produce the desired output:
fullNamePeople: Observable<{
firstName: string;
lastName: string;
fullName: string;
}[]>
To exhibit the final observable in an Angular context using the async pipe, variations of operators have been experimented with. However, the outcomes differ from initial expectations.
An attempt utilizing concatMap yields:
fullNamePeople: Observable<{
fullName: Observable<string>;
firstName: string;
lastName: string;
}>
It was anticipated that concatMap's functionality aligns with the objective, but this does not appear to be the case.
Switching to map results in an array yet still incorporates a nested observable:
fullNamePeople: Observable<{
fullName: Observable<string>;
firstName: string;
lastName: string;
}[]>
A solution achieved through the following implementation:
fullNamePeople = this.people.pipe(
mergeMap(people => people.map(person => this.fullName(person.firstName, person.lastName).pipe(
map(fullName => ({...person, fullName}))
))),
mergeAll(),
toArray()
);
Despite its success, concerns arise regarding efficiency and optimization of this approach.