Невозможно напечатать таблицу с * ngFor из json - PullRequest
0 голосов
/ 15 мая 2019

Этот конкретный Json не имеет ключа каждого элемента в массивах, мне удалось заставить эту работу работать с другими Jsons, которые приносят ключи элементов и используют эти ключи в {{data.key}} для печати с * ngFor.

Я перепробовал более 25 решений в stackoverflow, но, похоже, мой случай уникален, никто не использует JSON без keys / keys для создания таблицы.

Это мой Json:

{
    "data": {
        "spnf": {
            "anios": [
                "2018-Q4",
                "2018-Q4"
            ],
            "titulos": [
                "Ingresos Totales",
                "Balance Total"
            ],
            "anioactual": [
                3183,
                -837
            ],
            "anioanterior": [
                3672,
                1549
            ]
        },
        "gob_central": {
            "anios": [
                "2018-Q4",
                "2018-Q4"
            ],
            "titulos": [
                "Ingresos Totales",
                "Balance Total"
            ],
            "anioactual": [
                3183,
                -837
            ],
            "anioanterior": [
                3672,
                1549
            ]
        }
    }
}

Это мои balances.ts:

{

    this.loader.present().then(() => {
      this.finanzaService.getBalances2()
        .subscribe((result) => {
          this.dataRequest = result;
          this.setData();
          // Disable Loader
          this.loader.dismiss();
        }, (err) => {
          "error blah blah"
        }
        );
    });
  }

public setData(tipo: string = 'spnf') {

  if (tipo == 'spnf') {
    this.dataResumen = _.clone(this.dataRequest.spnf);
  } else {
    this.dataResumen = _.clone(this.dataRequest.gob_central);
  }
}

Это мой finanzapublica.service.ts:

 public getBalances2(): Observable<any>{
  const url = `${this.apiURL}/balances_fiscales/balances_datos2.json`;
  return this.http.get(url, this.options)
    .map((res: Response) =>  res.json().data);
}

Это мой balances.html, как только я пытаюсь использовать this.dataResumen, приложение ломает и выдает ошибку: Не удается найти другой поддерживающий объект '[object Object]' типа 'object'. NgFor поддерживает только привязку к итерациям, таким как массивы.

          <table *ngIf="dataRequest">
            <thead>
              <tr>
                <td class="border" text-center>Rubro</td>
                <td class="border" *ngFor="let data of this.dataResumen.anios" text-center>{{ data }}</td> <!--this works-->
              </tr>
            </thead>
            <tbody>
            <tr *ngFor="let data of this.dataResumen"><!--this doesn't work-->
             <td class="border" text-center>{{data.titulos}}</td>
             <td class="border" text-center>{{data.anioactual}}</td>
             <td class="border" text-center>{{data.anioanterior}}</td>
            </tr>
            </tbody>
          </table>

Это ошибка:

Cannot find a differ supporting object '{
  "anios": [
    "2018-Q4",
    "2018-Q4"
  ],
  "titulos": [
    "Ingresos Totales",
    "Balance Total"
  ],
  "anioactual": [
    3183,
    -837
  ],
  "anioanterior": [
    3672,
    1549
  ]
}' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

Результат, который я хотел получить, выглядит так:

Rubros             2018-Q4       2018-Q4
Ingresos Totales     3183         3672
Balance Total        -837         1549

1 Ответ

0 голосов
/ 16 мая 2019

        <table>
            <thead>
              <tr>
                <td class="border" text-center>Rubro</td>
                <td class="border" *ngFor="let data of dataResumen?.anios" text-center>{{ data }}</td> <!--this works-->
              </tr>
            </thead>
            <tbody>
              <tr *ngFor="let data of dataResumen.titulos; let i=index;">
                {{data}}
                <td>{{dataResumen.anioactual[i]}}</td>
                 <td>{{dataResumen.anioanterior[i]}}</td>
              </tr>

            </tbody>
          </table>
...