0
votes

I've created a Blazor Component within a full Blazor project and all works well. However, when I move this component to it's own Razor Class Library project, I am now getting an error that I cannot use JSInterop until a connection with the server is made. I am running my code in the OnAfterRenderAsync() method.

I had to alter the code a little when I made the change. In a full Blazor project, JSInterop is provided for you with DI in the Startup class. But this is not the case with a calss library.

So instead of "@inject JSInterop js" in the page, I had to set it up like this -

  private IJSRuntime js { get; set; }

  protected override void OnInitialized()
  {
    js = ScopedServices.GetRequiredService<IJSRuntime>();
  }

From the sketchy details available on the web, I'm assuming this gets the service from the Parent project.

Using debugging, I can see that js is NOT null. It does seem to have been set to a valid object.

Can anyone point me in the right direction?

2

2 Answers

0
votes

The server pre-renders, so your code will run before there is a client connection to the server. When rendering in OnAfterRenderAsync you should only use IJSRuntime when the firstRender parameter is true, or any point after that, but never before.

0
votes

Found the solution to my problem and it has rendered my initial question irrelevant. When I copied my component to it's own class library project, it would not compile. It gave me an error on the line @inject JSInterop js.

This led me to believe that it didn't know how to inject this as it is not set during the Startup of the project, as it is in a Blazor app. So I cobbled together the code to get a reference via ScopedServices.GetRequiredService(). This did create an object but did not have _clientProxy set which contains the connection to the server.

So digging round I managed to find a complete component library example project at BlazorHelp Website This did have the JSInterop injected in the Blazor file. So I reverted my code back to the original code that worked in the full project and tried to compile. It gave me the same error. So I deleted the @inject JSInterop js line and typed it in again. IT RECOGNIZED IT!!! It still failed to compile, not recognizing a custom type (Pivot) and asking whether I had included a reference to it.

[CascadingParameter] public Pivot OwnerPivot { get; set; }

I deleted the word Pivot and retyped it and, voila, it compiled.

So it looks like there some sort of error in VS2019 or the razor compiler, where deleting code in the source file and re-entering caused it to recognize and compile.