Is it me, or is the order of my operators not right? In the code below, the two taps with the console.logs return the same values. That can't be right right?
return this.pcs.getAvailableMaterials(currentProduct.id).pipe(
map(
result => result.result.data
),
tap(
x => console.log(x, 'before')
),
map(
materials => {
materials.forEach(material => {
material.type = 'material'
})
return materials
}
),
tap(
x => console.log(x, 'after')
),
tap(
materials => {
setState({
...state,
availableMaterials: materials
})
}
)
)
Angular 5 application with NGXS.
NOTE that @samanime's answer is not correct. Consider the following modification to your original code:
return this.pcs.getAvailableMaterials(currentProduct.id).pipe(
...
tap(
x => console.log(x, 'before')
),
map(
materials => {
materials.forEach(material => {
material.type = 'material'
})
return materials
}
),
delay(1000), // this line is new
tap(
x => console.log(x, 'after')
),
...
)
You still see both logs as the same. For @samanime's answer to be correct, console.log
would somehow have to be taking a full second to execute, which is certainly not the case.
The issue here is that RXJS expects pipe functions to be pure. That is, no pipe function should create any side effects that persist outside the execution of that function. In your first map
call, you mutate the objects inside the materials
array and then return a reference to the same array. This is a side effect. To fix this, you should be returning a new array from the first map
call. Something like:
map(
materials =>
materials.map(material => { // map instead of forEach makes a new array
return {...material, type: 'material'} // object spread makes new objects
})
)
This should give you what you expect.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments