javascript - 如何在 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
解决方案
您可以像这样简单地使用setItem
和getItem
:
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/
推荐阅读
- macos - 以编程方式禁用“摇动以查找指针”MacOS 功能而不隐藏光标
- laravel - Laravel 2 以相同的形式提交按钮
- java - 如何在 macOS 上为 IntelliJ 项目安装 Google OR-Tools
- git - git将未更改的文件添加到“未暂存的文件”中
- c++ - g++ 无法解决模板函数重载
- python-3.x - Python:导入日历错误给出了意想不到的结果
- python - 熊猫将列从一个数据框复制到另一个具有不同名称的数据框
- vue.js - VueJS 如何在方法中访问 Mounted() 变量
- php - ajax的成功函数不返回数据库中的所有行
- javascript - 自调用函数调用其他函数的问题