Reputation: 3
All questions related to this weren't getting a JSON in the first place.
I want to print a list of demands with ngFor. It doesn't show anything.
This is my html:
<div *ngFor="let item of DemandasList">
{{item.demandaName}}
</div>
This is my demandas.component:
import { Component, OnInit } from '@angular/core';
import { DemandasService } from './demandas.service';
@Component({
selector: 'app-demandas',
templateUrl: './demandas.component.html',
styleUrls: ['./demandas.component.css'],
providers: [DemandasService]
})
export class DemandasComponent implements OnInit {
constructor(private service:DemandasService, private modalService: NgbModal) { }
DemandasList:any=[];
ngOnInit(): void {
this.refreshDemList();
}
refreshDemList() {
this.service.getDemList().subscribe(data=> {
this.DemandasList=data;
console.log(this.DemandasList);
});
}
The console.log prints this: Console results
this is the service:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DemandasService {
readonly APIUrl="http://localhost:3440/api"
constructor(private http:HttpClient) {
}
getDemList():Observable<any[]> {
return this.http.get<any>(this.APIUrl+'/demandas');
}
}
thank you.
Upvotes: 0
Views: 113
Reputation: 3714
You have misspelled DemandasList
<div *ngFor="let item of DemandasList">
{{item.demandaName}}
</div>
Optional:
If You want I would suggest your code refactor.
Declare DemandasList
as Observable
demandasList$:Observable<any[]>;
If want to start with an empty array
demandasList$:Observable<any[]> = of([]);
Assign demandasList$ to a service call in ngOninit
ngOnInit(): void {
this.demandasList$ = this.service.getDemList();
// to console.log
// this.demandasList$ = this.service.getDemList().pipe(tap(console.log));
}
In template use AsyncPipe pipe to subscribe/unsubscribe
<div *ngFor="let item of DemandaList$ | async">
{{item.demandaName}}
</div>
If you want to show div on conditional
<div *ngIf="DemandaList$ | async as DemandaList; else loading">
<div *ngFor="let item of DemandaList">
{{item.demandaName}}
</div>
</div>
<ng-template #loading>
<div>Loading ...</div>
</ng-template>
Imports used
import { of, Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
Upvotes: 2