I hope everyone just doing fine. Can, please someone clearly explains which one to choose among pipe and subscribe, and why? when it comes to not only getting the response but also to initialize some other variables or make changes to the boolean variables.
Also have a look at the code. Is it the right way to do it?
public getAlbums(){
this.enableLoader = false;
this.albumHttpService.getAlbums()
.pipe(
map((response) => {
this.enableLoader = false;
if (!response.albums.length) {
this.noDataSet = true;
if (response.albums === null) {
this.list = [];
}
}
else{
this.noDataSet = false;
this.list = response.albums;
}
}),
catchError((error) => {
this.noDataSet = false;
this.data = [];
throw new Error(error);
})
)
.subscribe();
}
Thanks in advance
Pipe basically takes the output of the function and gives it as input to another function. It is a really great and efficient way to manipulate data and it is really powerful.
We are basically piping the output of something into a different function that can modify the incoming data or just to extra logic on top of the data (trigger side effects).
We can have multiple logics chained in the pipe operator.
Subscribe is called on an observable to subscribe to the final data that is pushed out from the observable.
Quick Example: I have an observable which sends a string "World".
worldObservable$.pipe(
tap(data=>console.log(data)), // Prints "World"
map(data=> `Hello ${data}`)
)
.subscribe(data=>console.log(data)); // Prints "Hello World"
In this example, first I use tap to get the data and then log it.
Next, I modify the data using the map operator which changes the initial data.
When I then subscribe it logs the modified data, instead of the initial data.
I hope it gave you some more clarity.
Within pipe you can concatenate many other functions and use these functions to write some logic, prepare the data for the view and etc.
subscribe is like the last point, where you get ready data and it is better not to write any logic there, just only assignments to your viewmodels or etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With