首页 > 解决方案 > 如何在 Angular 本地存储中定位单个对象值?

问题描述

在我的 Angular 应用程序maan中,我的数据库中有字段。我在前端显示该字段的值两次。一个是静态的,而其他值会改变。

我正在使用 Angular Local Storage 来保存saveChanges函数中的动态值。我正在使用新变量来存储值

var change_single_object = JSON.parse(localStorage.getItem('LikeWhen') || '{}') as LikeWhen
change_single_object.maan= maan; -------> Here I am trying to access dynamic value (#term reference in html)

但是上面的语句总是指静态值。我该如何解决这个问题?

界面

export interface LikeWhen {
    maan: string;  
}

组件.ts

export class RufusComponent { 
  @ViewChild('term') editElem!: ElementRef<HTMLTableDataCellElement>;
  
saveChanges(rec: LikeWhen, new_value: HTMLTableDataCellElement) {
 localStorage.setItem('LikeWhen', JSON.stringify(rec));
 var change_single_object = JSON.parse(localStorage.getItem('LikeWhen') || '{}') as LikeWhen
 change_single_object.maan= maan;-------------> PROBLEM (Refers to static value)

 localStorage.setItem('LikeWhen', JSON.stringify(change_single_object));
}
}

.html

// --------static value
 <mat-list-item>Static Value Amazon</mat-list-item>
            <mat-list>{{latestData.maan}}</mat-list>
            <mat-divider></mat-divider>

// -------dynamic value
            <mat-list-item>Dynamic Value</mat-list-item>
            <mat-list class="textFields">
                <table>
                    <tr>
                        <td [innerHTML]='latestData.replaceHTML' #term></td>
                    </tr>
                </table>                
            </mat-list>

//button
<button mat-raised-button type='button' [disabled]='confirmDisabled' (click)='saveChanges(latestData, term)'>Confirm

标签: javascriptangulartypescriptlocal-storage

解决方案


您可以像这样简单地使用setItemgetItem

localStorage.setItem('myCat', 'Tom');

const cat = localStorage.getItem('myCat');

有关这方面的更多信息,您可以查看:https ://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

要在某些事件或某事上动态更新数据,您可以使用角度服务和rxjs主题,如下所示:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {
  localStorage: Storage;

  changes$ = new Subject();

  constructor() {
    this.localStorage   = window.localStorage;
  }

  get(key: string): any {
    if (this.isLocalStorageSupported) {
      return JSON.parse(this.localStorage.getItem(key));
    }

    return null;
  }

  set(key: string, value: any): boolean {
    if (this.isLocalStorageSupported) {
      this.localStorage.setItem(key, JSON.stringify(value));
      this.changes$.next({
        type: 'set',
        key,
        value
      });
      return true;
    }

    return false;
  }

  remove(key: string): boolean {
    if (this.isLocalStorageSupported) {
      this.localStorage.removeItem(key);
      this.changes$.next({
        type: 'remove',
        key
      });
      return true;
    }

    return false;
  }

  get isLocalStorageSupported(): boolean {
    return !!this.localStorage
  }
}

此链接将对此提供更多帮助:https ://firstclassjs.com/persist-data-using-local-storage-and-angular/


推荐阅读