PWA Fundvelo der Caritas.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

UserDataProvider.cs 2.5KB

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