1

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!

2
  • There are a lot of things wrong with your current code. May I ask, have you tried following the tour of heroes at angular.io? Commented Dec 5, 2018 at 21:54
  • no, i found this code on stackover flow, like I said, the data does get displayed on console. Im just having trouble displaying it. Will check out heroes at angular.io though, thank you :) Commented Dec 5, 2018 at 22:10

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried using this.httpdata.push(data); but it still does not display anything.
ignore the first bit was just to show how .push() works, its not what you need, read from below, check edit :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.