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.
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.
Share asked Mar 26, 2018 at 20:43 DirkDirk 1751 gold badge2 silver badges13 bronze badges 3-
What is the type of
this.pcs.getAvailableMaterials(currentProduct.id)
? Is it an RXJS observable? – ethan.roday Commented Mar 26, 2018 at 20:50 - Can you make a demo showing what doesn't work as you expect? – martin Commented Mar 26, 2018 at 20:54
- @err1100 Yes the function returns a observable (http call) – Dirk Commented Mar 26, 2018 at 20:57
1 Answer
Reset to default 10NOTE 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.