Chris
Chris

Reputation: 85

Blazor same page component multiple routes

I have a blazor page component which has two routes.

For examples:

@page "/contacts" @page "/humanresources"

If you come in via /contacts a search is performed for a specific type of person and if you come in via humanresources a slightly different search is run. This is working fine but has an issue when going between contacts and humanresources as the page doesn't realise it's changed. There are NO parameters just two different routes. OnParametersSetAsync doesn't seem to work just for a route change.

How do I detect that the route has changed and I need to re-run some code?

Upvotes: 2

Views: 1455

Answers (1)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30016

The routes are interpreted by the Router and mapped to a component. If the route changes, but the component remains the same, there's no new component to load. Under normal circumstances a parameter of one sort or another changes, so the Renderer calls SetParametersAsync which calls OnParametersSet{Async}. However, if nothing changes, then it won't get called, which appears to be the case in your code.

In your case you can wire up the LocationChanged event on the NavigationManager like this:

@page "/"
@page "/counter"
@using System.Diagnostics;
@inject NavigationManager NavManager
@implements IDisposable
<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />
<div class="alert alert-dark">
    @this.Message
</div>
@code {
    private string Message = "Not Set";

    protected override void OnInitialized()
    {
        this.NavManager.LocationChanged += OnLocationChange;
    }

    protected override void OnParametersSet()
    {
        Debug.WriteLine("Parameters Set");
        base.OnParametersSet();
        Message = $"Parameters Set at {DateTime.Now.ToLongTimeString()}";
    }

    private void OnLocationChange(object? sender, LocationChangedEventArgs e)
    {
        Debug.WriteLine("Location Changed");
        Message = $"Location Changed at {DateTime.Now.ToLongTimeString()}";
        this.InvokeAsync(StateHasChanged);
    }

    public void Dispose()
        => this.NavManager.LocationChanged -= OnLocationChange;
}

Upvotes: 5

Related Questions