Ioni c Angular отображение и анализ JSON данных из API - PullRequest
0 голосов
/ 30 марта 2020

У меня есть этот образец JSON Формат данных из нашего API

{
    "type": "BasicResponse",
    "name": "",
    "serverId": "",
    "requestId": "",
    "output": {
      "Result": {
        "ListSequence": [
          {
            "status": "ORDER PROCESSED",
            "date": "",
            "comment3": "",
            "comment4": "",
            "comment1": "",
            "time": "",
            "comment2": ""
          },
        ],
        "RESULT": "SUCCESS"
      }
    },
    "status": {
      "success": true,
      "returnCode": 0
    }
  }

Я хочу отображать значение только для всего статуса (например, ЗАКАЗАТЬ ОБРАБОТАНО), пока он отображается так в моем html страница Кстати, я следовал за этим гидом .

enter image description here

Вот моя страница.ts

constructor(private dataService: DataService, private http: HttpClient) {
  this.data = '';
  this.error = '';
 }

 private prepareDataRequest(): Observable<object> {
  // Define the data URL
  const dataUrl = '';
  // Prepare the request
  return this.http.get(dataUrl);
}

ionViewWillEnter() {
  // Load the data
  this.prepareDataRequest()
    .subscribe(
      data => {
        // Set the data to display in the template
        this.data = JSON.stringify(data);
      },
      err => {
        // Set the error information to display in the template
        this.error = `An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`;
      }
    );
}

Вот моя страница. html

<p *ngIf="!error;else errorContent">{{ data ? data : '-' }}</p>
  <ng-template #errorContent><p><span style="color: red;">{{error}}</span></p></ng-template>

Ответы [ 2 ]

1 голос
/ 30 марта 2020

JSON.stringify является противоположностью того, что вам действительно нужно здесь. Я предполагаю, что «только для всех состояний» вы хотите отобразить свойство status из всех элементов массива ListSequence. Если да, то все статусы могут быть напрямую извлечены в его собственный массив с помощью .map() и отображены. Попробуйте следующее

public statuses = [];

private prepareDataRequest(): Observable<any> {  // <-- change return type here
  // Define the data URL
  const dataUrl = '';
  // Prepare the request
  return this.http.get(dataUrl);
}

ionViewWillEnter() {
  // Load the data
  this.prepareDataRequest().subscribe(
    data => {
      // Set the data to display in the template
      this.statuses = data.output.Result.ListSequence
        .map(item => {
          console.log('item.status: ', item.status);   // <-- log the `status` here
          if (item.status && item.status !== '') {
            return item.status;
          } else {
            return '-';
          }
        });    // <-- add closing bracket here
    },
    err => {
      // Set the error information to display in the template
      this.error = `An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`;
    }
  );
}

Шаблон

<ng-container *ngIf="!error; else errorContent">
  <p *ngFor="let status of statuses">
    {{ status }}
  </p>
</ng-container>
<ng-template #errorContent>
  <p>
    <span style="color: red;">{{error}}</span>
  </p>
</ng-template>
0 голосов
/ 30 марта 2020

До L oop через все статусы, используйте директиву *ngFor. В Component. html добавьте следующий код:

<div *ngFor="let result of data?.output?.Result?.ListSequence">
        <p> {{ result.status }} </p>
   </div>

Вот рабочий пример: Рабочая демонстрация

Или, для более чистого кода, объявите переменную в component.ts и присвойте ему значение ListSequence.

publi c resultArray :any[] = [];

protected someMethod(){
    ...
   this.resultArray = data.output.Result.ListSequence;
....
}

, а затем в файле компонента. html, который можно использовать список как ниже:

<div *ngFor="let result of resultArray">
        <p> {{ result.status }} </p>
   </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...