【问题标题】:Angular 6: how do I add a JSON string to an existing JSON string-array?Angular 6:如何将 JSON 字符串添加到现有的 JSON 字符串数组?
【发布时间】:2019-02-25 06:20:45
【问题描述】:

所以我有一个 Typescript 组件,其构造函数如下所示:

constructor(private http: HttpClient) {
    this.http.get('/api/values/users').subscribe(result => {
      this.values = result as string[];
    }, error => console.error(error));
  }

如您所见,它创建了一个字符串数组并将其存储在值中。我稍后在 html 中显示这个字符串 [] 类似这样的 sn-p

<tr *ngFor="let value of values; index as i">
      <td>
        <input [(ngModel)]="value.id" class="form-control" type="text" name="{{value.id}}" />
      </td>
</tr>

问题是我以后想在 JSON 格式的字符串数组中添加一个新元素。但是当我写

this.values.push("{id: 1, username: , firstName: , lastName: , token: ,}");

它与 JSON 格式不匹配,因此字符串变为:

0: {id: 2, name: "provider", password: "gps", roles: 4, status: 1}
1: {id: 4, name: "Josh", password: "pass", roles: 1, status: 1}
2: {id: 5, name: "admin", password: "admin", roles: 1, status: 1}
3: "{id: 1, username: , firstName: , lastName: , token: ,}"

注意最后一个值有双引号。这使得前面提到的 *ngFor 不会将其视为 JSON 格式,而只是认为这里的第四个对象只是一个常规字符串。 请帮帮我!

【问题讨论】:

  • values 成员不是string 数组,而是{id:number,name:string,password:string, roles:number,status:number} 数组。将其转换为字符串这一事实对对象的反序列化形式没有影响。这就是为什么你不能简单地将一个字符串推入你的数组。
  • "只是认为这里的第四个对象只是一个普通字符串" - ...因为它只是一个普通字符串,这就是你放入数组中。

标签: arrays json angular typescript angular6


【解决方案1】:

您必须执行 Object.assign()。这是一个将返回值对象与具有新元素的新对象合并的示例。

this.values= Object.assign({},this.values,{newElementFieldName: this.newObject});

【讨论】:

    【解决方案2】:

    字符串JSON 格式缺少引号。 试试下面的语法:

    this.values.push(JSON.parse('{"id": "1", "username": null, 
    "firstName": null, "lastName": null, "token": ","}'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多