I have a heavy task(fetching data) in my OnInitialized() when I navigate to that page using link from another page it freezing until the heavy task end, how can I show a general loading animation while navgating between pages.
-
1The big question is of course: why is that "heavy task(fetching data)" not async? Because if that could use async I/O you would have an elegant _and_ efficient solution. – H H Apr 29 '20 at 10:27
2 Answers
Most importantly, to prevent your page from freezing use the OnInitializedAsync method instead of OnInitialized.
In the view portion of your Component Page you may add code like the following to query if your data (list of person objects) is still unavailable:
@if (people == null)
{
<p>Loading people...</p>
}
else
{
<ul class="people-list">
@foreach (var person in people)
{
<li class="people-list-item">
<a href="@person.Id">
<PersonCard Person="person" />
</a>
</li>
}
</ul>
}
As long as the data is not available, the message "Loading people..." is displayed. When the data is available, it will be displayed instead of the message above. Instead of the message you can display animation, such as MatProgressBar. You can even simply place an img element with loading animation image instead of or in addition to the text message...
Hope this helps...

- 41,195
- 5
- 76
- 113
If you want to show/hide spinner or progress-bar write a Javascript function like this ,We suppose that you use NProgress (a javascript plugin to show spinner and progress-bar it is not important):
window.progress = (action=> {
if (action === "start") NProgress.start();
else if (action === "stop") NProgress.done();
};
Then you can start and stop it :
JSRuntime.InvokeVoidAsync("progress", "start");
// do the heavy process
JSRuntime.InvokeVoidAsync("progress", "stop");
If you want to show the progress, you need to have a SignalR Hub, then your JavaScript is like this :
connection.on("ReceiveProgress", function (progress) {
if (progress <= 100) NProgress.set(progress / 100);
else NProgress.done();
});
And in the Hub :
public async static Task SetProgress(int total, int index)
{
int progress = 0;
if (total != 0) progress = Convert.ToInt32(Math.Ceiling((double)(index * 100) / (double)total));
else progress = 0;
await _hubContext.Clients.User(State.User.Current.Id).SendAsync("ReceiveProgress", progress);
}
Now in your Blazor code increase the progress :
for(int i = 1 ; i<= total; i++)
{
// do the process step by step
await Noty.SetProgress(total, i);
}

- 941
- 10
- 18