首页 > 解决方案 > 如何在不删除键的情况下从对象和嵌套对象中重置值

问题描述

我创建了与多个组件共享数据的服务。毕竟,流程结束了,我需要重置服务对象的值。所以我尝试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(),

  }
}

一旦我将数据传递到后端,那么我需要重置为默认值服务文件

标签: javascriptangulartypescriptobjectangular6

解决方案


你为什么不创建一个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());


推荐阅读