Reputation: 10717
I was trying to show mat spinner on API method call. Below is my API call code on which I subscribe to get the data, Usually it is just 2 min work but this time didn't work, also I know this happens due to a subscribe method so any easy way to implement that?
this.loading = true;
this.ticketModelService.farmerList
.subscribe(value => {
if (value) {
this.farmerList = value.data;
this.paginationNumbers = value.recordsFiltered
}
})
this.loading = false;
Upvotes: 1
Views: 6245
Reputation: 1
The problem with your code is that you are not waiting for your subscription to happen. JavaScript/ Typescript is a synchronous language by default. So it doesn't wait for API call to complete before executing the next line i.e. this.loading = false;
So, the solution is to hide the spinner when the API call is complete. To do that we have to write the this.loading = false;
inside the callback function of the subscribe.
For example, in the html file,
<mat-spinner *ngIf="loading"></mat-spinner>
And in the typescript part,
this.loading = true;
this.ticketModelService.farmerList.subscribe({
next: (value) => {
if (value) {
this.farmerList = value.data;
this.paginationNumbers = value.recordsFiltered
}
},
complete: () => {
this.loading = false;
}
})
Upvotes: 0
Reputation: 674
I think your issue is your spinner appears and suddenly disappears. So here your loading variable will not wait for API to process and it will disappear within ms. So you should hide your loader in your API callback. So until you're API is processing, loader will stay there. And after getting response you can hide you're loader even if it's an error.
this.loading = true;
this.ticketModelService.farmerList
.subscribe(value => {
this.loading = false;
if (value) {
this.farmerList = value.data;
this.paginationNumbers = value.recordsFiltered
}
})
Update your code as above.
Upvotes: 4