Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying JSON Data in Angular Component

Tags:

angular

I have a service that is getting data from the server

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from "rxjs/Observable";

@Injectable()
export class CardService {

    private url = "http://192.168.100.112:8080/angular";

  constructor(private http: HttpClient) { }

  getCards(): Observable<any>{
  return this.http.get<any>(this.url);
 }
}

And it works fine with my component:

import { Component, OnInit } from '@angular/core';
import { CardService } from '../../services/card.service';

@Component({
    selector: 'cards-list',
    templateUrl: './card.component.html',
    styleUrls: ['./card.component.css']
  })
  export class CardComponent implements OnInit {

  private cardData: any;

  constructor(private svc: CardService) { }

  ngOnInit() {
    this.svc.getCards().subscribe(data =>{
      this.cardData = data;
      console.log(this.cardData)
    })
  }
}

The console is displaying the data I am trying to show on the app.component.html

but the data is not being displayed on the website:

appcomponent.html

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <cards-list></cards-list>
</div>

card.component.html

<div *ngIf="cardData">
  <ul>
    <li *ngFor="let card of cardData">
       <span>{{card.name}}</span>
       <span>{{card.id}}</span>
       <span>{{card.progress}}</span>
       <span>{{card.issue}}</span>
    </li>
  </ul>
</div>

Does anyone know what I am doing wrong?

enter image description here

like image 581
EAzevedo Avatar asked Oct 18 '25 07:10

EAzevedo


2 Answers

ngFor required an array for loop through. Response coming as an object. make carddata an array and push the response object.

  private cardData: any = [];

  constructor(private svc: CardService) { }

  ngOnInit() {
    this.svc.getCards().subscribe(data =>{
      this.cardData.push(data);
      console.log(this.cardData)
    })
  }
like image 94
Sachila Ranawaka Avatar answered Oct 19 '25 22:10

Sachila Ranawaka


This code will not work for a single object. You need to return the array even if the record length is 1.

<div *ngIf="cardData">
  <ul>
    <li *ngFor="let card of cardData">
       <span>{{card.name}}</span>
       <span>{{card.id}}</span>
       <span>{{card.progress}}</span>
       <span>{{card.issue}}</span>
    </li>
  </ul>
</div>
like image 35
Prachi Avatar answered Oct 19 '25 22:10

Prachi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!