Answer the question
In order to leave comments, you need to log in
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"
}
]
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){
}
}
<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>
<!--template bindings={
"ng-reflect-ng-for-of": null
}-->
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
Option 1 - get Observable
and use AsyncPipe
, which will do all the dirty work for us
releases: Observable<any[]>;
constructor(private releasesService: ReleasesService) {}
ngOnInit() {
this.releases = this.releasesService.getReleases();
}
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 questionAsk a Question
731 491 924 answers to any question