asp.net blazor项目添加Nuget包ReactiveUI和ReactiveUI.Blazor
创建视图模型BlogPostViewModel继承自ReactiveObject
- public class BlogPostViewModel : ReactiveObject
- {
- private readonly AnonymousBlogClient _http;
- public List
Categories { get; set; } - public BlogPost BlogPost { get; set; }
- public BlogPostViewModel(AnonymousBlogClient http)
- {
- _http = http;
- }
- public async Task Setup(string id)
- {
- try
- {
- BlogPost = await _http.GetBlogPostAsync(id);
- if (BlogPost == null) return;
- Categories = (await _http.GetCategoriesAsync())?.ToList();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex);
- }
- }
- }
添加根服务类的依赖注入
builder.Services.AddScoped();
BlogPostView.razor中添加继承
@inherits ReactiveComponentBase
blazor页面中添加代码
- [Parameter] public string id { get; set; }
- [Inject]
- public BlogPostViewModel BlogPostViewModel
- {
- get => ViewModel;
- set => ViewModel = value;
- }
完成