Blazored.LocalStorage 在客户服务中

Blazored.LocalStorage in client service

如何将 Blazored.LocalStorage (v2.1.6) 注入 blazor webassembly 服务 (3.2.0)?

这是我们尝试过的。尝试等待 LocalStorage.GetItemAsync.

时出现空错误

App.razor

@using Blazored.LocalStorage

Program.cs

builder.Services.AddBlazoredLocalStorage();
builder.Services.AddSingleton<Services.UserService>();

Services/UserService.cs

namespace Test.Client.Services
{
    public class UserService
    {
        [Inject]
        private ILocalStorageService LocalStorage;
        private readonly HttpClient Http;

        public UserService(HttpClient _http)
        {
            Http = _http;
        }

        public async void LoginCallback()
        {
            string tkn = await LocalStorage.GetItemAsync<string>("tkn"); //Object null error here
        }
    }
}

编辑解决方案: 首先,重新启动 Visual Studio 因为它正在坚持某些东西并且在我这样做之前不会对任何东西起作用。然后如标记的答案所示,DI 是这样的:

        private ILocalStorageService LocalStorage;
        private readonly HttpClient Http;

        public UserService(HttpClient _http, ILocalStorageService _localStorage)
        {
            Http = _http;
            LocalStorage = _localStorage;
        }

您必须先使用 @inject <IService> <serviceInstanceName>

进行注入

示例:

@using Blazored.SessionStorage
@inject ISessionStorageService sessionStorageService
...
@code
{
     var eml = sessionStorage.sessionStorageService.GetItemAsync<string>("emailAddress");
}

编辑:抱歉我误解了。以上是将session storage注入razor页面。如果你想注入一个 class 你做下面的事情:

public class SomeClass
{
    private ISessionStorageService _sessionStorageService;
        

    // inject in the class constructor
    public SomeClass(ISessionStorageService sessionStorageService)
    {
        _sessionStorageService = sessionStorageService;
    }
}

这是在您已经完成的Program.cs(在客户端)中注册服务的基础。

我遇到了同样的问题并尝试重新启动我的 Visual Studio 以及我的计算机,但都没有帮助,但后来发现这有点相关 post: https://github.com/dotnet/aspnetcore/issues/10143

显然,如果在 OnInitializedAsync 函数中获取数据,我们需要检查是否为 null,就像在 FetchData.razor 示例中一样:

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{