P粉4968866462023-09-01 10:39:42
You created the variable:
@emlpoyee
But you are calling @Employee
, which will be null.
Try switching to the variable you actually put in the employee:
@emlpoyee
Also, I think you spelled the variable wrong. Maybe you mean @employee.
You filled everything in here:
emlpoyee = await emp.Employee();
So, from the code you provided, it makes sense to call @emlpoyee.
So change <div> @Employee ... </div>
to <div> @emlpoyee ... </div>
P粉5133162212023-09-01 09:57:36
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:
namespace Hydra.Services { public interface IEmployee { Task<EmployeeModel> GetEmployee(); } }
Then, you need to modify your service to inherit from the above interface as follows:
namespace Hydra.Services { public class Employee:IEmployee { public async Task<EmployeeModel> GetEmployee() { // 返回JSON数据 } } }
Now you should inject the service in Startup.cs
or Program.cs
like this:
services.AddScoped<IEmployee,Employee>();
Finally, you should inject your service in the required component as shown below and use it easily:
@page "/" @using Hydra.Services @inherits OwningComponentBase<IEmployee> <div> @company ... </div> <!-- OK,公司详细信息已呈现 --> <div> @Employee ... </div> <!-- System.NullReferenceException: '对象引用未设置为对象的实例。' --> @code { private string company; private EmployeeModel emlpoyee = new EmployeeModel; private IEmployee employeeService => Service; protected override async Task OnInitializedAsync() // 获取公司详细信息 // 这里是问题所在: EmployeeModel emp = new EmployeeModel(); emp.url = "http://google.com"; emlpoyee = await employeeService.GetEmployee(); }
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.