Nick Mehrdad Babaki
Nick Mehrdad Babaki

Reputation: 12505

Angular: Doing job when loading http data using HttpClient, Observable and async pipe

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

Answers (1)

Fateh Mohamed
Fateh Mohamed

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

Related Questions