'How to combine two objects into one
i have two observables that get data from Input A and B from the dom
const observable1 = fromEvent(this.input1.nativeElement,'keyup').pipe(map((res) => {
const data: TestFilter = {
name : this.input1.nativeElement.value
}
this.filterService.changeMessage(data)
})).subscribe()
And second
const observable2 = this.input2.pipe(map(res => {
this.typesArray.push(res)
const data: TestFilter = {
types : this.typesArray
}
this.filterService.changeMessage(data)
})).subscribe()
In both cases, i use map to assign the input value to a data object that has the type TestFilter which can take these values:
name?: string,
types?: string[]
character?: string[]
Then, the data object gets passed down to another service.
The problem:
If the user inputs something and observable1 is triggered, a list gets filtered based on that input. If the user is now inputting something else into observable2, the previous input is lost because a separate data object is sent.
My approach When input 2 is triggered after Input one, Input 2 must re emit the last known value of input one and then merge both values into one data object which is then passed down. i tried to combine both with mergewith, but that doesnt work
observable1.pipe(mergeWith( observable2.pipe(map((res) => {
this.typesArray.push(res)} )) ),
tap((res) => {
const data: TestFilter = {
name : this.input.nativeElement.value,
types : this.typesArray
}
this.filterService.changeMessage(data)
})
)
.subscribe();
Solution 1:[1]
You need to use combineLatest so you can get both values entered in both fields. The gotcha is that all have to emit at least once.
const o$ = combineLatest(observable1, observable2).subscribe(
([input1, input2]) => { ... }
);
I will also update the observable1 in your code to use "startWith" operator setting the default value to emit.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eddie Paz |
