我正在跟踪NDC Oslo的一个示例应用程序,即该应用程序: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 firstRender)上执行代码,该错误消失了,但是绑定到API请求的网格没有显示。 API请求必须填充网格的数据源,该数据源必须为 OnInitializedAsync 。有任何解决方法吗?
更新! 我移动了代码OnAfterRenderAsync并添加了StateHasChanged方法,然后得到了所需的行为。 我忘记了用于渲染的连接是signalR连接。
答案 0 :(得分:1)
根据“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();
}
}