angular - прочитать имя свойства из JSON как имя столбца и показать другое значение свойства в столбце - PullRequest
0 голосов
/ 09 октября 2018

У меня есть файл json в структуре (показывает один из его объектов) как

[
...
{
        "Tag": "YearOfOperation",
        "Type": 9,
        "Value": "2018"
    }
...
]

в HTML-шаблоне У меня есть таблица.В строке «Год работы» таблицы я хочу отобразить «2018».Я пытаюсь перебрать json (то есть найти по имени строки / тега) и отобразить «Значение» json.В html-шаблоне я хочу что-то вроде:

<table>
<tr>
<td> Year Of Operation </td> // row name is hard coded. it doesn't depend on json
<td> display json "Value" where "Tag"=="YearOfOperation" </td>
</tr>
</table>

app.component.ts

public productData: any;


ngOnInit() {
            this.getJSON().subscribe(res => {
                this.productData = JSON.parse(res);
            })
        }

public getJSON(): Observable<any> {
        return this.http.get('./images/output_test.json')
            .pipe(
                map(res => res)
            )
        // .catch((error:any) => console.log(error));

    }

Заранее спасибо.

1 Ответ

0 голосов
/ 09 октября 2018

Если ваш JSON что-то вроде ниже и я правильно понял ваш вопрос, то это то, что должно работать для вас:

app.json

[
  { "Tag":"Location", "type": 9, "Value":"Europe" },
  { "Tag":"Location", "type": 10, "Value":"US" },
  { "Tag":"YearOfOperation", "type": 9, "Value":"2016" },
  { "Tag":"YearOfOperation", "type": 10, "Value":"2018" },
  { "Tag":"TaxId", "type": 9, "Value":"txn123" },
  { "Tag":"TaxId", "type": 10, "Value":"txn124" }
]

app.component.html

<table>
  <thead><tr><th>Location</th><th>Year Of Operation</th><th>Tax ID</th></tr></thead>
  <tbody>
    <tr *ngFor="let product of products">
      <td *ngIf="product?.Tag === 'Location'; else blankValue">{{product?.Value}}</td>
      <td *ngIf="product?.Tag === 'YearOfOperation'; else blankValue">{{product?.Value}}</td>
      <td *ngIf="product?.Tag === 'TaxId'; else blankValue">{{product?.Value}}</td>
    </tr>
  </tbody>
</table>
<ng-template #blankValue><td></td></ng-template>

app.component.ts

public products: any;

ngOnInit() {
    this.getJSON().subscribe(res => {
      this.products = <Array<{}>>res;
    })
}

public getJSON(): Observable<any> {
    return this.http.get('./images/output_test.json')
    .pipe(
      map(res => res),
      catchError((error) => { console.error(error); return error;})
    );
}

app.component.css

th {
    padding:10px;
    border:1px solid black;
}

td {
    padding:10px;
    border:1px solid black;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...