【问题标题】:How to return multiple result in new line using JSON.parse in Angular?如何在 Angular 中使用 JSON.parse 在新行中返回多个结果?
【发布时间】:2019-04-01 17:04:47
【问题描述】:

我有多个结果的 json 文件。

1 -- 样本一 jsonChanges: "{"field":"cancerType","oldValue":"Lentigo maligna melanoma","newValue":"Primary malignant melanoma of g canal"}"

在这种情况下,我成功地从列表中返回所有值

2 -- 采样两个多重值 jsonChanges: "{"field":"date","oldValue":"","newValue":"Tue Mar 26 00:00:00 GMT 2019"}, {"field":"techniqueType","oldValue":"","newValue":"Intralesional"},{"field":"response","oldValue":"","newValue":"Complete Response"}"

在这种情况下,它返回空。

在我使用的 component.ts 中

   getList(patientId?: number, pageNo?: number) {
        const auditTrailSubscription = 
        this._auditTrailService.getAuditTrailUrl(patientId, pageNo, 
        GridConfig.ITEMS_PER_PAGE)
          .subscribe(
           result => {
            try {
              this.totalItems = result.recordsCount;
              this.auditTrailList = result.lstRecords;
              this.auditTrailList.forEach(x => x.jsonChanges = 
          JSON.parse(x.jsonChanges));          
          } catch (e) {
            console.log(e);
          }
        },
        err => {
          this.handleError(err);
        }
      );

    this.addSubscription("auditTrail", auditTrailSubscription);
  }

在我正在使用的 html 中

   <tr *ngFor="let at of auditTrailList | paginate: { itemsPerPage: 
      _ITEMS_PER_PAGE, currentPage: crtPage, totalItems: totalItems }"
        [attr.data-row-id]="at.userId">
        <td>{{ at.userName }}</td>
        <td>{{ at.timestamp | date:  CUSTOM_DATE_FORMAT  }}</td>
        <td>{{ at.entityName }}</td>
        <td>{{ at.jsonChanges.field }}</td>
        <td>{{ at.jsonChanges.oldValue }}</td>
        <td>{{ at.jsonChanges.newValue }}</td>
      </tr>

页面是这样的

https://imgur.com/BE9BYsS

我的问题是如何获取多个值并在新行中显示它们。对于返回单个值是可以的。但是对于多个值我不知道。

【问题讨论】:

  • 示例 (2) 中的代码不是有效的 JSON 字符串。它应该包装在一个数组中。您可以通过手动添加括号JSON.parse(`[${x.jsonChanges}]`) 来解决此问题;但是,如果可能,我建议尝试在 API 中解决此问题。
  • 手动@Gasim 我无法访问后端。这个值是动态的。我只是使用我自己的服务(由后端发送的 URL)。在我的情况下,当用户更改一些值时有 2 个表,它会自动将新数据保存到新表中。我只是从这个表中获取数据。这个 jsonChanges 只是简单的字符串而不是数组。对于一行值 field>oldvalue>newvalue JSON.parse 返回值没有任何问题,但在多行的情况下会引发语法错误。
  • @Gasim 不幸的是,他们关闭了后端任务,我需要自己弄清楚。顺便说一句,JSON.parse([${x.jsonChanges}]) 不起作用,什么也不返回,但不会在控制台中抛出异常。

标签: javascript json angular typescript


【解决方案1】:

你可以在你的组件中使用这个代码:

this.str='{"field":"referringPhysician","oldValue":"Medical oncologist","newValue":"Cardiac surgeon"},{"field":"cancerType","oldValue":"Lentigo maligna melanoma","newValue":"Primary malignant melanoma of g canal"}';
this.arrData=this.str.split('},');
this.arrData.forEach((val, key) => {
  if(key != this.arrData.length-1){
    this.allData.push(JSON.parse(val+'}'));
  }else{
    this.allData.push(JSON.parse(val));
  }
});
console.log(this.allData);

那么你必须在你的 html 文件中使用 *ngFor

【讨论】:

  • 我试过了,但不幸的是它仍然返回空。
  • 在我的这段代码中显示(在控制台中):0: {field: "referringPhysician", oldValue: "Medical oncologist", newValue: "Cardiac surgeon"} 1: {field: "cancerType", oldValue: "Lentigo maligna melanoma", newValue: "Primary malignant melanoma of g canal"}。你能在你实现我的例子的地方展示你的代码吗?
  • 我不能导致代码太长。但是我用了你的方法。实际上 this.str 它不是这样的静态值。我从数据库中得到 json。而这个格式字符串中的json。对于返回单行更改,例如 1 个字段 => oldValue & newValue 它可以工作。对于多种情况不要
  • 是的,this.str 是静态的,供您理解。您可以将您的字符串放入this.str,其中字符串 json 来自您的数据库,然后查看您的控制台进行测试。
  • 这是SyntaxError ,可能是您在拨打电话时在JSON.parse 内犯了一些错误。你能告诉我你使用我的方法的那部分吗
【解决方案2】:

添加额外的数组并从此数组中获取结果解决了我的解决方案。

     try {
        this.results = [];
        this.totalItems = result.recordsCount;
        this.auditTrailList = result.lstRecords;
        this.auditTrailList.forEach(x => {
          const jschanges = JSON.parse(`[${x.jsonChanges}]`);
          jschanges.forEach(z => {
            this.results.push({
              userName: x.userName,
              timestamp: x.timestamp,
              entityName: x.entityName,
              field: z.field,
              oldValue: z.oldValue,
              newValue: z.newValue
            })
          })
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多