I am new to Angular and trying to figure out how to read and display the contents of a json file.
Component.ts
import { Component, OnInit } from '@angular/core';
import { RoomService } from '../shared/room.service';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
public httpdata=[];
constructor(private roomservice:RoomService) {
}
ngOnInit() {
this.roomservice.getJSON().subscribe(data => {
this.httpdata.push=data;
console.log(data);
});
}
}
.html
<div>
<ul *ngFor="let t of httpdata ">
{{t.id |json}}
</ul>
</div>
I am able to obtain the data using console.log but not able to display the data.
My JSON:
{
"rooms":[
{
"id": "1",
"name": "abd",
"Description": "blah blah",
"Settings": {
"Sources": ["ass","fff"],
"hex": "#000"
}
},
{
"id": "2",
"name": "abc",
"Description": "blah",
"Settings": {
"Sources": ["sss,ddd"],
"hex": "#000"
}
}
]
}
Any help appreciated!
you are not pushing to the array correctly, it would look like below
this.httpdata.push(data);
That should populate your array properly if that was what you needed, although i think below is what should be happening from the code provided. Starting inside the subscription.
ngOnInit() {
this.roomservice.getJSON().subscribe(data => {
this.httpdata = data.rooms;
console.log(this.httpdata);
});
}
And then in the template
<div>
<ul *ngFor="let rooms of httpdata ">
<li>{{ rooms.id }}</li>
</ul>
</div>
Good place to have a read Angular tutorial