Home > Enterprise >  Using HttpClient to make get requests
Using HttpClient to make get requests

Time:10-23

I have written the following code to get the dummy data here:

export class AppComponent {
    
  jsonPosts: any = [];

  constructor(private httpClient: HttpClient) { }

  OnInit() {
    this.getJsonPosts();
  }

  getJsonPosts(): any {
    return this.httpClient.get("https://jsonplaceholder.typicode.com/posts")
      .subscribe(response => {
        console.log(response);
        this.jsonPosts = response;
      });
  }

I have also written the following code to display them in my HTML template:

  <ul *ngFor="let i of jsonPosts">
    <li>{{i.userId}}</li>
    <li>{{i.id}}</li>
    <li>{{i.title}}</li>
    <li>{{i.body}}</li>
  </ul>

However, there is no network activity at all, and thus nothing shows...

What am I doing wrong here?

CodePudding user response:

You are not calling OnInit method. If you want to let angular lifecycle call your method, your component has to implement OnInit interface with ngOnInit method.

More here.

So your component code should look like this:

export class AppComponent implements OnInit {
    
  jsonPosts: any = [];

  constructor(private httpClient: HttpClient) { }

  ngOnInit(): void {
    this.getJsonPosts();
  }

  getJsonPosts(): any {
    return this.httpClient.get("https://jsonplaceholder.typicode.com/posts")
      .subscribe(response => {
        console.log(response);
        this.jsonPosts = response;
      });
  }
  • Related