Angular 4 使用@angular/http 作为HttpModule 包来获取数据,较新版本使用@angular/common/http 具有HttpClientModule。
HttpClient 已经以 JSON 格式获取数据,因此您实际上不需要 .json() 方法,因为您的响应已经是 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;
});
}
}
同样对于未来,最好使用构造函数只注入依赖,并使用OnInit生命周期从API中获取数据
@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;
});
}
}
基于从 json 占位符带来的帖子类型,这是一个正确的方法:
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;
});
}
}
更新。已添加Stackblitz 示例。