Unable to call service in Blazor component
P粉351138462
2023-08-31 12:01:02
<p>I have a service that looks like this: </p>
<pre class="brush:php;toolbar:false;">namespace Hydra.Services
{
public class Employee
{
public string url { get; set; }
public async Task<EmployeeModel> GetEmployee(){
// Return JSON data
}
}
}</pre>
<p>I want to call this service in my <code>Company</code> component: </p>
<pre class="brush:php;toolbar:false;">@page "/"
<div> @company ... </div> <!-- OK, company details have been rendered -->
<div> @Employee ... </div> <!-- System.NullReferenceException: 'The object reference is not set to an instance of an object. ' -->
@code {
company string;
emlpoyee string;
protected override async Task OnInitializedAsync()
using (HttpClient client = new HttpClient())
{
// Get company details
// Here's the problem:
EmployeeModel emp = new Employee();
emp.url = "http://google.com";
emlpoyee = await emp.Employee();
}
}
}</pre>
<p>So, there's nothing wrong with the logic of displaying the company, but the Employee service I'm calling inside using() doesn't seem to work. I don't know what the problem is other than the error. </p>
<p>It's not a matter of forgetting to include a model or inject a service. </p>
<p>I am just a beginner, so the questions are relatively simple. </p>
You created the variable:
But you are calling
@Employee
, which will be null.Try switching to the variable you actually put in the employee:
Also, I think you spelled the variable wrong. Maybe you mean @employee.
You filled everything in here:
So, from the code you provided, it makes sense to call @emlpoyee.
So change
<div> @Employee ... </div>
to<div> @emlpoyee ... </div>
Your code does not perform service injection correctly. I present to you a method that I use and it works correctly, I hope it will be useful to you.
First, you need to create an interface for your service:
Then, you need to modify your service to inherit from the above interface as follows:
Now you should inject the service in
Startup.cs
orProgram.cs
like this:Finally, you should inject your service in the required component as shown below and use it easily:
Of course, your code has a lot of structural problems, and you may just want to specify the problem in the form of example code, so I tried to explain how it works using your own code so that the example is more specific to you.