Reputation: 12505
I am using HttpClient in an angular 6 application to load data. I need to do some extra job when data loaded successfully. If I use subscribe function I can easily do that inside subscribe like:
http.get("/addressOfService").subscribe(data=>{
this.info =data;
DoJob();
});
But I know the best practice to load data and use it in a view is using async pipe as long as possible, so I am using it. Now my question is what is the best practice to run a function when data is loaded and the user is using an async pipe. I have tried some different solution and found out I can use map function, something like:
http.get("/addressOfService").pipe(map(data=>{
DoJob();
return data;
}));
But I am not sure if it is a good practice.
Upvotes: 0
Views: 64
Reputation: 21377
you should use tap instead to perform side effects because map apply a function to change each element emitted and it's not your case here
getData() {
this.isLoading = true;
http.get("/addressOfService").pipe(tap(_ => {
DoJob();
this.isLoading = false; // in case of success hide loading spinner
}));
}
Upvotes: 5