Reputation: 2965
I am working on Angular 5 with Http.
Getting this error while serve the application..
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-post-detail',
templateUrl: './post-detail.component.html',
styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
body: string;
recent: {};
constructor(
private route: ActivatedRoute,
private router: Router,
private http: HttpClient,
) { }
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
let userId = this.route.snapshot.paramMap.get('userid');
this.getUserPosts(userId);
this.http.get('https://jsonplaceholder.typicode.com/posts/'+id)
.subscribe((data)=>{
this.body = data.body;
});
}
}
I dont know Why I am getting this error and I assign the type as string in the class based on the syntax.
Response of API as below,
Upvotes: 1
Views: 2929
Reputation: 2851
(data)=>{
this.body = data.body;
}
data
is not json. You need to run .json()
on data
. Or you could run map
before subscribe:
this.http.get('https://jsonplaceholder.typicode.com/posts/'+id)
.map(res => res.json())
.subscribe((data)=>{
this.body = data.body;
});
In order to use map
, you need to import it:
import 'rxjs/add/operator/map'
See more examples here: https://angular.io/api/http/Http
EDIT:
The response is typed - you need to create an interface for the response:
interface SomeResponse {
Body: SomeType;
}
And make the request like this:
this.http.get<SomeResponse>'https://jsonplaceholder.typicode.com/posts/'+id)
.subscribe((data)=>{
this.body = data.body;
});
Again, more examples here: https://codingthesmartway.com/angular-4-3-httpclient-accessing-rest-web-services-with-angular/
Upvotes: 1