A
A
Alexander Belov2017-01-08 23:05:35
Angular
Alexander Belov, 2017-01-08 23:05:35

How to get json data in Angular2 app?

There is a separate json file on the locale like:

[
    {
      "name": "Release One",
      "source": { "pointer": "/data/attributes/first-name" },
      "songs":  "Release One Songs",
      "year": "2010"
    },
    {
      "name": "Release Two",
      "source": { "pointer": "/data/attributes/first-name" },
      "songs":  "Release Two Songs",
      "year": "2011"
    },
    {
      "name": "Release Three",
      "source": { "pointer": "/data/attributes/first-name" },
      "songs":  "Release Three Songs",
      "year": "2014"
    }
  ]

How to load data into the view of an Angular2 application?
Tried a bunch of tutorials, something is outdated and doesn't work, something just causes errors due to the fact that the starter project is built differently.
releases.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';

@Injectable()
export class ReleasesService {
  constructor(private http: Http){

  }

  getReleases(){
    return this.http.request('./releases/releases.json')
    .map(res => res.json());
  }

  getData(res: Response){

  }
}

releases.component.html
<div class="releases-component">
  Releases Component starts here!
  <div *ngFor="let release of releases">
    <h3>Name: {{release.name}}</h3>
    <h3>Name: {{release.year}}</h3>
  </div>
</div>

Nothing is displayed in the view. In the inspector, instead of the expected objects:
<!--template bindings={
  "ng-reflect-ng-for-of": null
}-->

releases.component.ts
import { Component, OnInit } from '@angular/core';
import { ReleasesService } from './releases.service';

@Component({
  selector: 'releases',
  templateUrl: './releases.component.html',
  styleUrls: ['./releases.component.scss']
})
export class ReleasesComponent implements OnInit { 
  constructor(){

  }

  ngOnInit(){

  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2017-01-08
@AlexanderBelov

Option 1 - get Observableand use AsyncPipe, which will do all the dirty work for us

releases: Observable<any[]>;

constructor(private releasesService: ReleasesService) {}

ngOnInit() {
  this.releases = this.releasesService.getReleases();
}

Option 2 - sign up yourself
releases: any[];

constructor(private releasesService: ReleasesService) {}

ngOnInit() {
  this.releasesService.getReleases()
     .subscribe(data => this.releases = data);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question