Angular2 parsing from JSON to object
It's because in Angular tutorial, json is in the data property.
As stated in the tutorial
Make no assumptions about the server API. Not all servers return an object with a data property.
If you are not wrapping your json with any property you can just use
private extractData(res: Response) { let body = res.json(); return body || { }; //<--- not wrapped with data}
Update:
Component code
onSearch(terms: string) { this.searchService.search(this.user, terms).subscribe( (response: SearchResponse) => { // <--- cast here console.log(response); }, error => { console.log(JSON.stringify(error)); }, () => { } ); }
I am quite late to this topic but found my self into the same issue . I am learning Angular and want to convert JSON received from HTTP server to my model object .
Service Class
var ele:User;let k=this.http.get<User>(url).subscribe(data => { ele=data; console.log(ele.count); console.log(ele.results[0].first_name); console.log(ele.results[0].profile.gender); } );
My Model for holding the information of JSON
export interface User{ count: string; next: string; previous: string; results: Result[];}export interface Result{ pk: string; first_name: string; last_name: string; profile:Profile;}export interface Profile{ pk: string; gender:string;}
And this is it. I am using Angular 6 for parsing JSON to Object