Как отформатировать JSON выборку данных из API - PullRequest
0 голосов
/ 01 апреля 2020

Я получаю данные из API и пытаюсь отобразить их в своем приложении angular. Я могу получить и отобразить данные, но они не в хорошем формате.

{
    "countryCode": "BS",
    "countryName": "BAHAMAS",
    "publishedDate": "2020-03-30T00:00:00.000Z",
    "alertMessage": "\nAll international flights to Uganda are suspended until 24 April 2020.|\n- This does not apply to:|\n1. Aircraft in a state of emergency.||\n2. Operations related to humanitarian aid, medical and relief flights.||\n3. Technical landings where passengers do not disembark.||\n4. Any other flight that may be so approved by the appropriate authority.||\n"
},
{
    "countryCode": "FJ",
    "countryName": "FIJI",
    "publishedDate": "2020-03-30T00:00:00.000Z",
    "alertMessage": "\n1. Passengers and airline crew are not allowed to enter Fiji.|\n- This does not apply to nationals of Fiji.||\n2. Nationals of Fiji must go into quarantine for a period of 14 days.||\n"
}

JSON данные, которые Я получаю из API.

Ожидаемый вывод:

enter image description here

, но вывод, который получается,

enter image description here

мой код следующим образом

<div class="card" style="width: 69rem;" *ngFor="let alert of jsonValue">
          <div class="card-body" #{{alert.countryName}}>
            <div class="container">
              <div class="row">
                <div class="col">
                  <span> <p class="card-title h2" style="float: left">{{alert.countryName}}</p></span>
                </div>
                <div class="col">
                  <span><img src="../../../assets/flags/{{alert.countryCode | lowercase}}.svg" style="width: 40px; height: 28px;"></span>
                </div>
              </div>
            </div>
            <p class="card-text">{{alert.alertMessage}}</p>
            <p class="card-footer" style="float: right">{{alert.publishedDate | date:'short'}}</p>
          </div>
        </div>

Ответы [ 2 ]

1 голос
/ 01 апреля 2020

Текст необычно отформатирован. Один из способов его использования - разделить строку в соответствии с вашими требованиями и выполнить итерацию, используя *ngFor.

var alertMessage = '\nAll international flights to Uganda are suspended until 24 April 2020.|\n- This does not apply to:|\n1. Aircraft in a state of emergency.||\n2. Operations related to humanitarian aid, medical and relief flights.||\n3. Technical landings where passengers do not disembark.||\n4. Any other flight that may be so approved by the appropriate authority.||\n';

console.log(alertMessage.split(/[||\n]+/).filter(Boolean))  // <-- `filter(Boolean)` to remove empty strings

Затем вы можете использовать его в компоненте следующим образом:

Служба извлечения данных из API

@Injectable()
export class ApiService {
  ...
  getData() {
    this.http.getData().pipe(
      .map(data =>
        data.forEach(item => {
          item.alertMessage = item.alertMessage.split(/[||\n]+/).filter(Boolean)
        })
      )
    );
  }
}

Шаблон компонента

<div class="card" style="width: 69rem;" *ngFor="let alert of jsonValue">
  <div class="card-body" #{{alert.countryName}}>
    <div class="container">
      <div class="row">
        <div class="col">
          <span> <p class="card-title h2" style="float: left">{{alert.countryName}}</p></span>
        </div>
        <div class="col">
          <span><img src="../../../assets/flags/{{alert.countryCode | lowercase}}.svg" style="width: 40px; height: 28px;"></span>
        </div>
      </div>
    </div>
    <p class="card-text">
      <ul [ngStyle]="{'list-style': 'none', 'padding-left': '0'}">
        <li *ngFor="let message of alert.alertMessage">{{ message }}</li>
      </ul>
    </p>
    <p class="card-footer" style="float: right">{{alert.publishedDate | date:'short'}}</p>
  </div>
</div>
0 голосов
/ 01 апреля 2020

Может быть, вы захотите отформатировать свои данные перед использованием в шаблоне. Строка содержит \n и |, что имеет особое значение. Вы можете использовать их для форматирования ваших данных.

Например, допустим, вы получаете эти данные из сервиса внутри метода someMethod(). После получения данных l oop по элементам массива результатов и создания нового массива для всех элементов ответа, содержащих отформатированные значения.

  someMethod(){
         .... other lines to fetch the data

         let data = {
        "countryCode": "BS",
        "countryName": "BAHAMAS",
        "publishedDate": "2020-03-30T00:00:00.000Z",
        "alertMessage": "\nAll international flights to Uganda are suspended until 24 April 2020.|\n- This does not apply to:|\n1. Aircraft in a state of emergency.||\n2. Operations related to humanitarian aid, medical and relief flights.||\n3. Technical landings where passengers do not disembark.||\n4. Any other flight that may be so approved by the appropriate authority.||\n"
    }

 let arr = str.split('|').filter((el)=>{ return el!== ""}); // splits the string and removes empty element
 let newArr = arr.map((el)=>{ return el.replace("\n" ,"")}) // removes \n from string
// of course you can minimise/reduce the logic , this is just to make you understand how the formatting happened
 let formattedValues = { 
                   title : newArr[0],  // first element is title
                   subtitle : newArr[1], // second is subtitle  
                   options : newArr.slice(2) // rest is option
                   }
    data['alertMessage'] = formattedValues; // assign the formatted value
    } 

, затем в HTML вы можете использовать JSON как ниже:

 <p class="card-text">{{alert.messageData.title}}</p>
            <p class="card-text">{{alert.messageData.subtitle}}</p>
              <p *ngFor="let it of alert.messageData.options">{{it}}</p>

Вот рабочий пример: Демо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...