How to use NavigationManager in a class outside razor page?

Viewed 4256

I got a singleton class Globals, and I like to have a static method to navigate to other pages across my app.

public class Globals
{
    public static async void openBlazorPage( string pageName )
    {
        await Task.Run( () => { NavigationManager.NavigateTo( pageName ); } );
    }
}

but I can not access NavigationManager in this class.

  • how to access NavigationManager in a class outside razor page ?
1 Answers

To access NavigationManager inside component code behind class outside of Razor page, use [Inject] attribute like below -

public class EmployeeEditBase : ComponentBase
    {
        [Inject]
        public NavigationManager NavigationManager { get; set; }

}

Make sure to use code behind approach for components.

For using inside any service, use constructor injection. In your case you can use constructor inject too.

public class Globals
{
private readonly NavigationManager _navMagager;
public Globals(NavigationManager navManager)
{
  _navMagager = navManager;
}

    public static async void openBlazorPage( string pageName )
    {
        await Task.Run( () => { _navMagager .NavigateTo( pageName ); } );
    }
}

Hope, it'll help you. Thanks

Related