0

Am getting data from API and trying to display it in my angular application I can able to fetch and display the data but it's not in a good format.

{
    "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 data which I get from API.

The output which is expecting is

enter image description here

but the output which am getting is

enter image description here

my code as follows

<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>
1
  • 1
    It's not going to become a numbered list without your doing any work! If you want newlines an d whitespace to be significant, you can wrap it in <pre> or use CSS. If you want a bulleted list, you need to parse your string Commented Apr 1, 2020 at 19:12

2 Answers 2

1

The text is unusually formatted. One way to use it is to split the string as per your requirement and iterate it using *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

You could then use it in the component like following

Service fetching data from API

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

Component template

<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>
Sign up to request clarification or add additional context in comments.

5 Comments

Don't you mean<ol><li *ngFor ...?
I want to display complete JSON data I mean country name and alert message if I use this I can only get the alert message right??
@JuanMendes: Yeah it be could iterated over a list but weirdly the text already contains the numbers. That is why I said it is unusually formatted.
@NaveenKumar: The HTML was only supposed to be a placeholder. You could include all other tags from your post. Nevertheless, I've updated my answer.
@NaveenKumar check my answer
0

May be you want to do some formatting to your data before using it in the template. The string contains \n and | which has a special meaning. You can use them to format your data.

for Example let say you are getting this data from service inside a method someMethod() . After getting the data loop over the result array elements and create a new Array for all the response items containing the formatted values.

  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
    } 

then in HTML you can use the JSON as below :

 <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>

Here is the working example : Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.