PWA Fundvelo der Caritas.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

UserDataProvider.cs 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using cwebplusApp.Shared.Models;
  2. using Microsoft.JSInterop;
  3. using System;
  4. using System.Threading.Tasks;
  5. namespace cwebplusApp.Shared.Services {
  6. public sealed class UserDataProvider {
  7. private const string KeyName = "account";
  8. private readonly IJSRuntime _jsRuntime;
  9. private bool _initialized;
  10. private UserData _data = new();
  11. public UserData Data {
  12. get => _data;
  13. set => _data = value;
  14. }
  15. public event EventHandler Changed;
  16. public bool AutoSave { get; set; } = true;
  17. public UserDataProvider(IJSRuntime jsRuntime) {
  18. _jsRuntime = jsRuntime;
  19. }
  20. public async ValueTask<UserData> Get() {
  21. // Register the Storage event handler. This handler calls OnStorageUpdated when the storage changed.
  22. // This way, you can reload the settings when another instance of the application (tab / window) save the settings
  23. if (!_initialized) {
  24. // Create a reference to the current object, so the JS function can call the public method "OnStorageUpdated"
  25. var reference = DotNetObjectReference.Create(this);
  26. await _jsRuntime.InvokeVoidAsync("BlazorRegisterStorageEvent", reference);
  27. _initialized = true;
  28. }
  29. // Read the JSON string that contains the data from the local storage
  30. UserData result;
  31. var str = await _jsRuntime.InvokeAsync<string>("BlazorGetLocalStorage", KeyName);
  32. if (str != null) {
  33. result = System.Text.Json.JsonSerializer.Deserialize<UserData>(str) ?? new UserData();
  34. } else {
  35. result = new UserData();
  36. }
  37. _data = result;
  38. return result;
  39. }
  40. public async Task Save() {
  41. var json = System.Text.Json.JsonSerializer.Serialize(_data);
  42. await _jsRuntime.InvokeVoidAsync("BlazorSetLocalStorage", KeyName, json);
  43. }
  44. // This method is called from BlazorRegisterStorageEvent when the storage changed
  45. [JSInvokable]
  46. public void OnStorageUpdated(string key) {
  47. if (key == KeyName) {
  48. // Reset the settings. The next call to Get will reload the data
  49. _data = null;
  50. Changed?.Invoke(this, EventArgs.Empty);
  51. }
  52. }
  53. }
  54. }