Issue
Suppose we have two observables
student$ = from([
{id: 1, name: "Alex"},
{id: 2, name: "Marry"},
])
address$ = from([
{id: 1, location: "Chicago", sid: 1},
{id: 2, location: "Florida", sid: 2},
])
I want to combine them into a array of object, the expected result would be following
studentAddress = [
{
id: 1,
name: "Alex",
address: [
{id: 1, location: "Chicago", sid: 1},
]
},
{
id: 2,
name: "Marry",
address: [
{id: 2, location: "Florida", sid: 2},
]
},
]
Solution
Considering your students$
and address$
observable emits an array of objects.
address$ = of([
{ id: 1, location: 'Chicago', sid: 1 },
{ id: 2, location: 'Florida', sid: 2 },
]);
students$ = of([
{ id: 1, name: 'Alex' },
{ id: 2, name: 'Marry' },
]);
Use RxJs function combineLatest: It Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables.
combineLatest
will not emit an initial value until each observable emits at least one value
combineLatest(
[this.students$, this.address$],
(students, address) =>
students.map((s) => ({
...s,
address: address.filter((a) => a.sid === s.id),
})) // combineLatest also takes an optional projection function
).subscribe(console.log);
imports used :
import { combineLatest, of } from 'rxjs';
Angular Demo by using combineLatest
and forkJoin
Note: In your case instead of combibeLatest
you can use forkJoin. forkJoin
only emits value When all observables are complete, emit the last emitted value from each.
Answered By - navnath
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.