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?
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)
})
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With