The operator map
is a transformer, what it does is that it takes the value that touches it in the chain of operators in pipe
and returns a new value based on that, which could be the input value of another operator or be the final value.
Suppose you get a number 2 in your API :
this.http.get(this.url).pipe(
map(n => { return n * 2}), // 2*2=4
map(n => { return n * 4}) // 4*4=16
)
The value at the end would be 16, because the original value was transformed through the map
. For that reason, you would be using it badly, because what you are interested in is creating a secondary effect from the value that comes in the HTTP response, not transforming that same response .
You could use the tap
operator instead, whose goal is exactly what you want to do: Use the response value without transforming it.
this.http.get(this.url).pipe(
tap(n => { console.log(n * 2)}), // 2*2=4
tap(n => { console.log(n * 4)}) // 2*4=8
)
Of course map
is working for you, as could filter
or so many other operators that exist in rxjs , but it's better to use tap
since it was created for that.
Now, on the other hand, you could accomplish the same thing in other ways that would make more sense. For example:
- Subscribing to Observable returned by
this.http.get()
would give you the same results ... But you would have to manage the life cycle of the subscription.
- You could also use
this.http.get(this.url).toPromise()
and handle yourself as if it were a Promise ... But it would be swimming in redundancy.
- Use
async pipe
. I strongly recommend this option , because it's simple, you do not have to handle the Observable life cycle and your code will look better. How to use async pipe