从OnInitializedAsync Blazor调用Java脚本时出现JavaScript互操作错误 [英] JavaScript interop Error when calling javascript from OnInitializedAsync Blazor

查看:11
本文介绍了从OnInitializedAsync Blazor调用Java脚本时出现JavaScript互操作错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注NDC奥斯陆的一个示例应用程序,这个应用程序:https://github.com/SteveSandersonMS/presentation-2019-06-NDCOslo/tree/master/demos/MissionControl。 这将JWT实现为身份验证和授权。但是,当我尝试将代码的实现复制到服务器端Blazor时,当我尝试从如下所述的本地存储中获取存储的JWT令牌时,我得到了一个错误"

JavaScript interop calls cannot be issued at this time. This is because the component is being 
statically rendererd. When prerendering is enabled, JavaScript interop calls can only be performed 
during the OnAfterRenderAsync lifecycle method.

这是我的运动夹克代码

protected override async Task OnInitializedAsync()
{
    var token = await TokenProvider.GetTokenAsync();
    Branches = await Http.GetJsonAsync<List<BranchDto>>(
        "vip/api/lookup/getbranches",
        new AuthenticationHeaderValue("Bearer", token));
}

错误来自

public async Task<string> GetTokenAsync()
{
   //Code Omitted for brevity 
   //This line of code is equivalent to the IJSRuntime.Invoke<string>("localstorage.getitem","authToken") 
   //change to use Blazore.LocalStorage.
    var token = await _localStorageService.GetItemAsync<string>("authToken");
    return token;
 }

我尝试在OnAfterRenderAsync(Bool First StRender)上执行代码,错误消失了,但绑定到API请求的网格没有显示。API请求必须填充网格的数据源,该数据源必须是OnInitializedAsync。有解决此问题的方法吗?

更新! 我将代码移到AfterRenderAsync并添加了StateHasChanged方法,获得了所需的行为。 我忘记了用于呈现的连接是SignalR连接。

推荐答案

根据"Detect when a Blazor Server app is prerendering",您只能在OnAfterRenderAsync生命周期方法中安全地运行互操作代码。

但是,由于此过程在呈现周期之后运行,因此您需要在异步进程完成后通知组件使用StateHasChanged()重新呈现:

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        var token = await TokenProvider.GetTokenAsync();
        Branches = await Http.GetJsonAsync<List<BranchDto>>(
            "vip/api/lookup/getbranches",
            new AuthenticationHeaderValue("Bearer", token));

        StateHasChanged();
    }
}

这篇关于从OnInitializedAsync Blazor调用Java脚本时出现JavaScript互操作错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆