Angular 4 used @angular/http
which as HttpModule
package to fetch data, newer versions use @angular/common/http
which has HttpClientModule
.
HttpClient
already fetches data in JSON format, so you don't really need .json()
method because your response is already a json.
@Component({
selector: "posts",
templateUrl: "./posts.component.html",
styleUrls: ["./posts.component.css"]
})
export class PostsComponent {
posts: any[];
constructor(http: HttpClient) {
http
.get("https://jsonplaceholder.typicode.com/posts/1")
.subscribe(response => {
this.posts = response;
});
}
}
Also for the future, it's better to use constructor to only inject dependencies and use OnInit
lifecycle to fetch data from APIs
@Component({
selector: "posts",
templateUrl: "./posts.component.html",
styleUrls: ["./posts.component.css"]
})
export class PostsComponent implements OnInit {
posts: any[];
constructor(private readonly http: HttpClient) {}
ngOnInit() {
this.http
.get("https://jsonplaceholder.typicode.com/posts/1")
.subscribe(response => {
this.posts = response;
});
}
}
Based on post type brought from json placeholder, this is a correct approach:
interface Post {
userId: number;
id: number;
title: string;
body: string;
}
@Component({
selector: "posts",
templateUrl: "./posts.component.html",
styleUrls: ["./posts.component.css"]
})
export class PostsComponent implements OnInit {
post: Post;
constructor(private readonly http: HttpClient) {}
ngOnInit() {
this.http
.get<Post>("https://jsonplaceholder.typicode.com/posts/1")
.subscribe(response => {
this.post = response;
});
}
}
Update. Have added Stackblitz example.