Search code examples
angularangular-httpclient

Angular http client module not displaying response


I am trying to call an API(JSONPlaceholder posts API) in Angular 6 but am having an issue getting any results in my template

This is the api coming from a service file

  private _url = 'https://jsonplaceholder.typicode.com/posts';
  constructor( ) { }

  getBU() {
    return this._url;
  }

My ts component

  ngOnInit(): void { // adding the lifecycle hook ngOnInit
    this.http.get<DataResponse>(this.api.getBU()).subscribe(data => {
      this.vals = [data];
    });
  }

Interface to get certain values

export interface DataResponse {
    userId: string;
    id: string;
    title: string;
}

Template to display results

  <li *ngFor="let item of vals">
      {{item.title}}
  </li> 

If I use this api https://jsonplaceholder.typicode.com/posts/1 then I can see the results


Solution

  • https://jsonplaceholder.typicode.com/posts url returns array of object and you are putting it into another array.

    Please try the following:

      ngOnInit(): void { // adding the lifecycle hook ngOnInit
          this.http.get<DataResponse[]>(this.api.getBU()).subscribe(data => {
               this.vals = data;
          });
      }