c# - Blazor 服务器:在 App.razor 中初始化的 Scoped 服务在 Page 中为空
问题描述
我在 blazor 服务器应用程序中使用这个 App.razor:
<CascadingValue Name="SessionID" Value="SessionID" TValue="Guid">
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, theres nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
</CascadingValue>
@code {
[Parameter] public Guid SessionID { get; set; }
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
sessionID.SessionID = SessionID;
cart = mySingleton.Get<Cart>(sessionID.SessionID) ?? new Cart(); // breakpoint (after page refresh) cart is set
}
}
然后在页面中我有这个:
@if (cart != null) // breakpoint executed next, cart is empty
{
<br />
<label><b>Cart Items:</b></label>
<br />
@foreach (var item in cart.lineCollection)
{
@item.PColor.displayValue
<br />
@item.PLabel.First().displayValue
<hr />
}
}
我将作用域服务注入到主 _Imports.razor 文件中的所有组件中:
@inject MySingleton mySingleton
@inject MyScopedSessionID sessionID
@inject Cart cart
购物车作为范围服务注入。当我调试它时(在填充购物车并刷新页面之后),首先,应用程序被执行并且购物车被正确设置了一个带有一些项目的购物车对象,然后页面被执行,但是购物车是空的并且页面上没有任何内容, 为什么会发生这种情况以及如何纠正这种情况?
编辑:
我意识到不应该完全分配服务,我创建了一个带有 Cart 属性的 Scoped 服务,然后分配了这个属性,现在可以工作了。
解决方案
推荐阅读
- python - 在 python 中出现错误“字符串索引超出范围”
- html - 如何在html中将元素设置为右侧?
- c# - C# - 将数字转换为最小 BitArray 的最快方法是什么
- django - 在 Axios、Vue JS 中使用 Django 模式传递 ID Mitch mech
- json - Pyspark Struct 列:爆炸后的奇怪行为
- java - 期间发生内部错误:“分析覆盖会话 java
".java.lang.IllegalArgumentException-代码覆盖 EclEmma in sts - informatica-cloud - iics 中的平面文件连接失败。连接的行为就像在 Windows 的运行时运行的 Unix 服务器
- javascript - 如何获取面包屑链接点击的价值
- reactjs - 打字稿:如何将 PropTypes.oneOf(Object.value(FOOBAR)) 转换为类型?
- node.js - Angular + Nodejs Express:错误跨域请求被阻止:同源策略不允许读取远程资源