Thank you for visiting my site!

Home / Angular Tutorials / Http Services

Http Services

    1. app.modules.ts
      add to imports:

      imports: [BrowserModule, AppRoutingModule, HttpClientModule],

      import to the top:
      import { HttpClientModule } from “@angular/common/http”;

    2. In the .component.ts file
       
      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;
          });
        }
      
      }
      
    3. In the .component.html file
       
      <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>
      
      
      

ADD YOUR COMMENT