(Blazor WASM) Getting RouteData in service

Viewed 292

In a simple app I'm building something like a state service that pulls data from the server fully driven by navigation. This forces me to have proper working routes for every state of the app and keeps my implementation clean and simple.

Core thing in my service is of course to subscribe to NavigationManager.LocationChanged and change the state accordingly. But although NavigationManager.Uri has everything I need, I lack the parsing of route variables that Router provides via RouteData and is available as CascadingParameter in pages and components.

How can I access the current RouteData whenever I handle the NavigationManager.LocationChanged in my service? Or how can I do this differently (react to navigation changes and change my service state accordingly)?

1 Answers

Add a component to handle passing RouteData to your service:

public class RouteDataHandler : ComponentBase
{
    [CascadingParameter(Name = "AppRouteData")] Microsoft.AspNetCore.Components.RouteData? routeData { get; set; }

    protected override void OnParametersSet()
    {
        // Pass it to a service
        base.OnParametersSet();
    }
}

Add the cascade to App.razor:

<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <CascadingValue Name="AppRouteData" Value="@routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        <RouteDataHandler />
        </CascadingValue>
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>
Related