javascript - 如何在不删除键的情况下从对象和嵌套对象中重置值
问题描述
我创建了与多个组件共享数据的服务。毕竟,流程结束了,我需要重置服务对象的值。所以我尝试this.UserDetails = {};
它清除值并删除嵌套对象。只需将值重置为默认分配为服务。
谢谢。
服务文件
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class dataService {
constructor() { }
UserDetails: any = {
key1 : '' ,
key2: {
Status: false,
Label: ''
},
key3: {
Status: false,
Label: ''
},
key4: {
Status: false,
Label: ''
},
key5: '',
key6: '',
key7: new Date(),
}
}
在组件中分配值后,它看起来像
UserDetails = {
key1 : 'value 1' ,
key2: {
Status: true,
Label: 'label 1'
},
key3: {
Status: false,
Label: 'label 2'
},
key4: {
Status: true,
Label: 'label 3'
},
key5: 'key value 1',
key6: 'key value 2',
key7: new Date(),
}
}
一旦我将数据传递到后端,那么我需要重置为默认值服务文件
解决方案
你为什么不创建一个UserDetails
类并用数据填充它。在重置期间,只需返回该类的一个新实例。
请参阅下面的演示片段,我使用 ES6 类来解释这个概念,但您可以将其扩展到 Angular。
class UserDetails {
key1 = '';
key2 = {
Status: false,
Label: ''
};
key3 = {
Status: false,
Label: ''
};
key4 = {
Status: false,
Label: ''
};
key5 = '';
key6 = '';
key7 = new Date();
}
class MyService {
userDetails;
constructor(){
this.userDetails = new UserDetails();
}
populate(){
this.userDetails.key1 ="foo"
this.userDetails.key2 = {
Status: true,
Label: 'bar'
};
return this.userDetails;
}
reset(){
this.userDetails = new UserDetails();
return this.userDetails;
}
}
let service = new MyService();
console.log(service.populate());
console.log("***********Resetting************");
console.log(service.reset());
推荐阅读
- r - 计算至少有一个值的行数
- laravel - Laravel 在保存到数据库之前转换日期格式
- python - 如果我想从字符串中创建一个树结构?
- c++ - 有没有办法自动实现 sprintf 的缓冲区分配?
- rust - 在 Rust 中使用 Rc 时,如何防止递归释放导致堆栈溢出?
- redux - 如何将 redux-sagas 与 react-hooks 一起使用
- go - 我已使用 gorilla 将其连接为客户端。连接后。如何在 GO 中关闭它?
- java - 如何使用开关按钮在 android studio 中停止通知?
- javascript - axios调用绑定数据到vue
- autodesk-forge - 将模型从 Autodesk Viewer 加载到 Forge Viewer