-
- app.modules.ts
add to imports:imports: [BrowserModule, AppRoutingModule, HttpClientModule],import to the top:
import { HttpClientModule } from “@angular/common/http”; - In the .component.ts file
[code lang=”js” highlight=”1,14,21″ toolbar=”true”]
import { HttpClient } from "@angular/common/http";
import { Component, OnInit } from "@angular/core";@Component({
selector: "app-posts",
templateUrl: "./posts.component.html",
styleUrls: ["./posts.component.scss"] })
export class PostsComponent implements OnInit {
posts: any = [];
//posts: Object;
private url = "https://jsonplaceholder.typicode.com/posts";constructor(private http: HttpClient) {
this.getPosts();
}ngOnInit() {
}private getPosts() {
this.http.get(this.url).subscribe(response => {
//console.log(response);
this.posts = response;
});
}}
[/code] - In the .component.html file
[code lang=”js” highlight=”4″ toolbar=”true”]
<div class="row">
<div class="col-xs-12">
<ul class="List-group">
<li *ngFor="let post of posts" class="list-group-item">
<h3>{{ post.title }}</h3>
<p>{{ post.body }}</p>
</li>
</ul>
</div>
</div> [/code]
- app.modules.ts