Get data from json file in Angular 2
I have a json file and I am trying to put this information into my project using a service in Angular 2. Here is my code:
This is my service:
import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class RecordsService {
data: any;
constructor(private http: Http) { }
getRecords(id) {
return this.http.get('../assets/data/03_data.json')
.map(data => {
this.data = data;
}, err => {
if (err) {
return err.json();
}
});
}
}
This is the component:
import { Component, OnInit } from '@angular/core';
import { RecordsService } from '../shared/services/records.service';
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css'],
providers: [RecordsService]
})
export class ContentComponent implements OnInit {
constructor(private recService: RecordsService) { }
ngOnInit() {
}
getRecords(id) {
this.recService.getRecords(id)
.subscribe(data => {
console.log(data);
}, err => {
console.log(err);
});
}
}
Can someone help me what I did wrong. Thank!
+3
source to share
2 answers
You don't call getRecords()
anywhere, so it won't run at all. We found out that it id
shouldn't be a parameter at all in getRecords()
. So call the method in OnInit
:
ngOnInit() {
this.getRecords();
}
also you need to return the actual json from the response i.e. .json()
So:
.map(data => {
this.data = data.json();
return data.json();
}
+2
source to share