How to load this JSON data into Angular2

Viewed 109

Im new to Angular2, I want to load this Json data and display in a page, Im not sure how to do..? From all sources I learnt I made a code and attached it below, But its not running because of some errors, can anyone help in fixing or writing a new code for me so that i can learn from it..

Thanks in advance for the help.

My code file - student.json

[ { "name": "John", "id_number": "12", "attendance": "276 days", "grade": "A" }, ], this is my students.service.ts code

    import {Injectable} from '@angular/core'; 
    import { Http, Response } from '@angular/http';



    @Injectable()
    export class StudentsService {

    constructor(private http:Http)
    { 
     }

    getStudents() {

    return this.http.get('./students.json')
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();


    }

    }

and, this is my students.component.ts file

    import {Component} from '@angular/core';
    import { Http, Response } from '@angular/http';
    import {StudentsService} from './students.service'; 
    import 'rxjs/add/operator/map'
    import 'rxjs/Rx';

    @Component({
    selector: 'students',
    templateUrl: 'students.html',
    styleUrls: ['./students.scss']
     }) 
     export class students    {

       public students;

        constructor( private _studentsService:StudentsService, private     http:Http)
        {
          this.students = this._studentsService.getStudents();
            }
        ngOnInit() {
         this._load();
         }

         private _load() {
         this.students = this._studentsService.getStudents();

         }

         }
4 Answers

You can write a service to load your html from json file and available all over your application like below.

@Injectable()
export class ConfigService {
  public config: any;
  private configObs: Observable<any>;

  constructor(private http: Http) {
   }

  public load(filename: string): Observable<any> {
    if ( this.config ) {
      return Observable.of(this.config);
    } else {
      this.configObs = this.http.get(filename).map((res) => {
        this.config = this.config || res.json() || {};
        return this.config;
      });
    }

    return this.configObs;
  }
}

You can also put your data in typescript class format if that option is available referance answer

If you have JSON data and you want to show it in page.

Use Data Table to show It.

Here is the example you can see how to show on page. Please click Here

Assign our json to a varible

 myData = [{
             "name": "John",
             "id_number": "12",
             "attendance": "276 days",
             "grade": "A"
          },
          ...
          ...
         ],

In your Html

<ul>
     <li *ngFor="let data of myData">
         <div>{{data.name}}</div>
         <div>{{data.id_number}}</div>
         <div>{{data.attendance}}</div>
         <div>{{data.grade}}</div>
     </li>
</ul>

Hope it helps

What you are dealing with is an Observable students, either you need to manually subscribe to that observable, or use the async pipe in the template which handles the subscribing for your.

Also you are now performing the request twice, in the constructor and in your OnInit. Remove one of those, I'd remove the one in the constructor, since I like to keep everything away from the constructor, that does not need to be there, like mentioned here: https://stackoverflow.com/a/35763811/6294072

Back to the subscribing... either do:

this.students = this._studentsService.getStudents();
<div *ngFor="let student of students | async">
  <p>{{student.name}}</p>
  <!-- ... -->
</div>

or:

this._studentsService.getStudents()
  .subscribe(students => {
     this.students = students;
  })
  <div *ngFor="let student of students">
    <p>{{student.name}}</p>
    <!-- ... -->
  </div>
Related