Reputation: 73
I'm trying to read the content of my JSON file through my "GetJsonService".
app.component.ts:
data: any;
constructor(private jsonService: GetJsonService) {}
ngOnInit() {
this.getRecords();
console.log(this.data);
}
getRecords() {
this.jsonService.getRecords().subscribe(data => {
this.data = data;
}, err => {
console.log(err);
});
}
get-json.service.ts
constructor(private http: Http) { }
data: any;
getRecords() {
return this.http.get('assets/standorte.json').map(data => {
this.data = data.json();
return data.json();
}, err => {
if (err) {
return err.json();
}
});
}
I want to put the content of data.json() into this.data to use it. But when I log this.data it is "undefined".
I'm completely new to Angular 2 and Typescript, so I really would be thankful when someone helps me.
Greetings
Upvotes: 0
Views: 2832
Reputation: 549
Just modify your method getRecords()
Use it as below :
getRecords() {
this.jsonService.getRecords().subscribe(data => {
this.data = data;
console.log(this.data);
}, err => {
console.log(err);
});
}
Instead of logging after calling method you should do inside success of service.
This is common issue which every developer face at initiate stage of Angular 2+. It is an async call. So the issue is you console.log() statement is executing before your service assign value this.data = data; to the variable.
With your code if you display data in HTML it will probably work fine. Just it will not log properly where you got confused.
Upvotes: 1
Reputation: 73
@MauricioSipmann solved my problem. The problem was that the code runs asynchronously in a request. I actually knew that but Typescript confused me a little bit.
Thank you to all responders!
Upvotes: 1
Reputation: 3778
another problem is your not re throw the async state ..try this:
ngOnInit() {
this.getRecords().then((resp)=>{
console.log(resp);
});
}
getRecords() {
return new Promise<>((resolve,reject)
=> {
this.jsonService.getRecords().subscribe(data => {
this.data = data;
resolve(data);
}, err => {
console.log(err);
reject(err);
});
})
}
Upvotes: 0
Reputation: 41407
If you are using angular 6, no need to convert to json. Just return the request.
getRecords() {
return this.http.get('assets/standorte.json')
}
Upvotes: 0