Iterate over json with angular 7 using services

I have a node server that returns the following JSON:

{
        "ResponseStatus": {
          "ResponseCode": 0,
          "ResponseMessage": "Success."
        },
        "Events": [
          {
            "CodEspec": 65957,
            "NomeEspec": "O PIOR ESPETÁCULO DO MUNDO",
            "DiaHoraEspecs": [
              "2019-05-09T21:30:00",
              "2019-05-10T21:30:00",
              "2019-05-25T21:30:00"
            ]
          },
          {
            "CodEspec": 01234,
            "NomeEspec": "O MELHOR ESPETÁCULO DO MUNDO",
            "DiaHoraEspecs": [
              "2019-05-09T21:30:00",
              "2019-05-10T21:30:00",
              "2019-05-25T21:30:00"
            ]
          },

        ]
      }

I created an angular service that executes a GET and returns the JSON.

tickeline.service.ts

getEventos():Observable<Event[]>{
    //get todos os eventos
    return this.http.get<Event[]>(this.url_node, httpOptions);
  }

Also created a model for the event to only get certain parameters:

events.ts

export class Event{

  CodEspec: number;
  NomeEspec: string;
  DiaHoraEspecs: Date[];

}

The in the event component where i want to show the JSON i call the function geteventos from the service.

events.component.ts

export class EventsComponent implements OnInit {

  events: Event[];

  constructor(private ticketlineservice: TicketlineService) { }

  ngOnInit() {
    this.ticketlineservice.getEventos().subscribe(events => {
      this.events = events;
    });
  }
}

events.component.html

<div class="text-center">
    <ul *ngFor="let event of events">
        <li class="btn bg-primary text-center">
            <h2>Evento:</h2> 
            <p>{{ event.NomeEspec }}</p>
            <p>{{ event.CodEspec }}</p>
            <p>{{ event.DiaHoraEspecs }}</p>
        </li>
    </ul>
</div>

Problem: Create for every Event object a li element with the corresponding information. At the moment it only creates on li element and doesn't show the JSON information

In this json which are you presenting Events is a property. So you should get this property from events in subscribe:

this.ticketlineservice.getEventos().subscribe(events => {
  this.events = events.Events;
});

But if you are getting array as response with Events property inside (as you mentioned it in comment), you should do this like this:

this.ticketlineservice.getEventos().subscribe(events => {
  this.events = events[0].Events;
});

And you should also in further steps change a type of return getEventos():Observable<Event[]> because as you showed this is not true (according to this sample JSON response). You are not returning Event array.

And also in HTML file you should make changes like @Dusan Radovanovic post as his answer. So it should like this:

<div class="text-center">
  <ul>
    <li class="btn bg-primary text-center" *ngFor="let event of events">
      <h2>Evento:</h2> 
      <p>{{ event.NomeEspec }}</p>
      <p>{{ event.CodEspec }}</p>
      <p>{{ event.DiaHoraEspecs }}</p>
    </li>
  </ul>
</div>

Iterate over json with angular 7 using services - node.js - html, Iterate over json with angular 7 using services - node.js. Instead of iterating over ul elements you should iterate over li elements <div class="text-center"> <ul >� Well, it's pretty obvious that it won't work, as there is no variable called data in the user.User.Stats path. It seems like there is a part of your business logic missing. When users should be filtered ou

Instead of iterating over ul elements you should iterate over li elements

 <div class="text-center">
        <ul>
            <li class="btn bg-primary text-center" *ngFor="let event of events">
                <h2>Evento:</h2> 
                <p>{{ event.NomeEspec }}</p>
                <p>{{ event.CodEspec }}</p>
                <p>{{ event.DiaHoraEspecs }}</p>
            </li>
        </ul>
    </div>

Iterating through JSON object with Angular 2 ngFor - json - html, Before I write a service to get json, I just want to use some dummy json to test the front end. What's the correct way to iterate through json with ngFor? I tried the� Using Angular forEach() with an Object. In the first example, I am creating an object named employees, which has an array of data in it, such as the date of joining, name and age of each employee. I’ll use the forEach() function to loop through each value in the object and extract the values and display it (in the console) one by one.

Your JSON is not an array, it is an object.

Inside your subscribe, I think you probably want to do this:

  this.events = events.Events;

As others have mentioned, with your current code you should create two ul lists. If you want to create a single list with two items you'll need something like this:

<ul >
    <li class="btn bg-primary text-center" *ngFor="let event of events">
        <h2>Evento:</h2> 
        <p>{{ event.NomeEspec }}</p>
        <p>{{ event.CodEspec }}</p>
        <p>{{ event.DiaHoraEspecs }}</p>
    </li>
</ul>

Moving the *ngFor from the ul to the li

KeyValuePipe, This examples show how an Object or a Map can be iterated by ngFor with the use of this keyvalue pipe. @Component({ selector: 'keyvalue-pipe', template:� Objects are not iterable and don’t have the forEach() method. If you really had to you can also use Object.entries(json) which would take all the properties and their values in the object and

There are two parts to your problem here.

From the response please pick the Events array and assign it to the events class level variable in event.component.ts

export class EventsComponent implements OnInit {

  events: Event[];

  constructor(private ticketlineservice: TicketlineService) { }

  ngOnInit() {
    this.ticketlineservice.getEventos().subscribe(events => {
      this.events = events.Events;// This is the change for getting only events from the response
    });
  }
}

This way you will have only the events array rather than the entire response.

The second step is to as pointed out by main run a loop on the li rather than the ul as shown below:

<div class="text-center">
        <ul>
            <li class="btn bg-primary text-center" *ngFor="let event of events">
                <h2>Evento:</h2> 
                <p>{{ event.NomeEspec }}</p>
                <p>{{ event.CodEspec }}</p>
                <p>{{ event.DiaHoraEspecs }}</p>
            </li>
        </ul>
    </div>

I would like to add one more good practice which is to add elvis operator or safe operator so that your HTML does not fail.

event.NomeEspec ---> event?.NomeEspec

This way if event is undefined then we are safely accessing the properties of the event object.

Update

getEventos():Observable<Event[]>{
    //get todos os eventos
    return this.http.get<Event[]>(this.url_node, httpOptions);
  }

here you are type casting the response to Event[] whcih you will have to change a bit as shown below.

**getEventos():Observable<Event[]>{
    //get todos os eventos
    return this.http.get<Event[]>(this.url_node, httpOptions).map(response=> response.Events);// map operstor takes your response and sends the Events array as a part of the response for your HTTP call.
  }**

Loop Object Key Values In Angular Using *NgFor & Angular , <p>Loop Through Object using KeyValue Pipe and *ngFor</p> <div *ngFor="let item of object | keyvalue"> {{item | json }} Object� How to use an observable data service. The data service exposes an observable, for example TodoStore exposes the todos observable. Each value of this observable is a new list of todos. The data service can then be used directly in the templates using the async pipe: This pipe will subscribe to the todos observable and retrieve its last value.

Convert json to array angular 6, How to write data to a json file in localhost using angular idea on javascript. How to iterate array of objects in angular 6 Convert array of object to an object this service in Angular and show in HTML page? if i have single json Apr 10, 2020 id in angular 7 ; Angular- Get value from nested object in JSON ; angular 7 SEO� Angular is a platform for building mobile and desktop web applications. Join the community of millions of developers who build compelling user interfaces with Angular.

How to iterate through JSON Object with members? � Issue #15 , Since methods like map and forEach doesn't exist for JSON Object with By clicking “Sign up for GitHub”, you agree to our terms of service and the title JSON object members and not array How to iterate through lock bot locked as resolved and limited conversation to collaborators on May 7, 2018. Iterating over an array is one of the most commonly faced problem in any programming language. In typescript, we have multiple ways to iterate an array. Using loops and using its inbuilt method forEach, we can iterate through the array elements. In this tutorial, I will show you different ways to do it with examples. Using a for loop :

For Of • Angular, You can't return from the enclosing function using a return statement. For In. The for-in loop is designed for iterating over an objects properties, like� KeyValue pipe released in Angular 6.1 to loop through objects,Maps and arrays.Now by passing KeyValue pipe to *ngFor we can loop through objects key values & maps. Prior to this Angular 6.1 release we cannot iterate directly through objects key values & maps using *ngFor directive. To tackle this issue Angular keyvalue pipe has been introduced.

Comments
  • You are getting repeated uls instead of lis, put your *ngFor over the li
  • what is the content of events which are returned in subscribe?
  • subscribe returns an array with two arrays inside and in those two is the information of every event
  • @LuisMaia but you showed the JSON response, and there is no array with arrays inside. You should be clear which response exactly you are getting.
  • @porgo returns the following: 0: Events: Array(2) 0: {...} 1: {...}
  • In the model of event i need to change anything? Because I´m getting the following error Type 'Event' is missing the following properties from type 'Event[]': length, pop, push, concat, and 26 more
  • this.events = events[0];, this.events returns the error in the comment above: Type 'Event' is missing the following properties from type 'Event[]': length, pop, push, concat, and 26 more
  • you are getting this because you have a return type Event[] from observable in your service, change this for any[]: getEventos():Observable<any[]>
  • Returns an error in the HTML Can´t iterate over an object ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object' i changed to *ng-repeat="event in events" but also returns an error Can't bind to 'ng-repeat' since it isn't a known property of 'li'.
  • I also checked once again the response you are getting, and I noticed my error (I think so). It should be: this.events = events[0].Events;.
  • Still only creates a single li element and doesn't show the JSON information
  • I already alter the html, but when I change the event.component.ts to this.events = events.Events; it returns the following error Property 'Events' does not exist on type 'Event[]'.
  • Hi @LuisMaia I have updated the answer please check if that helps.You need to pick the Events array from response before typecasting the response which you are doing when you say this.http.get<Event[]>.So please see the updated asnwer and let me know if it helps.