Reputation: 4896
How do you write a function that takes an Observable<T[]> and updates the value inside the observable. I tried with the below approach but i felt i am not doing the update on proper way. I want to update the values of the observable with the row object.
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
let gridData = [
{
id: '1',
firstName: 'Sophie',
lastName: 'Beckham',
gender: 'F',
jobTitle: 'Senior Associate-L1',
jobArea: 'London',
monthlyWage: '$100000',
},
{
id: '2',
firstName: 'Sophie',
lastName: 'Beckham',
gender: 'F',
jobTitle: 'Senior Associate-L2',
jobArea: 'London',
monthlyWage: '$100000',
},
{
id: '3',
firstName: 'Chloe',
lastName: 'Bryson',
gender: 'F',
jobTitle: 'Senior Associate-L3',
jobArea: 'London',
monthlyWage: '$100000',
},
];
let gridData$ = of(gridData);
let row = {
id: '2',
firstName: 'TAN',
lastName: 'Ara',
gender: 'M',
jobTitle: 'Senior Associate',
jobArea: 'ATL',
monthlyWage: '$130000',
}
gridData$.subscribe((val: any) => {
val.forEach((list: any) => {
if(list['id'] === row['id']){
for (const property in row) {
list[property] = row[property];
}
}
})
})
gridData$.subscribe((v) => console.log(v));
In my approach i have used for loop and based on the object id updating the value. If there is a better approach, kindly share your approach.
StackBlitz : https://stackblitz.com/edit/rxjs-gdgkyk?devtoolsheight=60
Upvotes: 2
Views: 3234
Reputation: 2727
Observables are stateless and its recommended that emitted values are immutable.
But you can return a new observable that returns what you want by using the map
operator (on all values).
Note that I've used from
instead of of
operator.
import { from } from 'rxjs';
import { map } from 'rxjs/operators';
...
let gridData$ = from(gridData);
...
gridData$ = gridData$.pipe(
map((val: any) => {
if(val['id'] === row['id']){
for (const property in row) {
val[property] = row[property];
}
}
return val;
})
);
gridData$.subscribe((v) => console.log(v));
Now each time you call gridData$
it will execute the new observable.
https://stackblitz.com/edit/rxjs-6mh6iu
Upvotes: 3