0
votes

I am trying to call an example API (https://jsonplaceholder.typicode.com/posts) in Angular via the use of an interface.

However I am getting the following error. ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}

My code for my TS file is below

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient } from '@angular/common/http';

interface Post {
  title: string;
  body: string;
};

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {


  constructor(public navCtrl: NavController, private http: HttpClient) {

  }

  ionViewDidLoad() {

    this.getData();

  }

  getData() {
    this.http.get<Post>('https://jsonplaceholder.typicode.com/posts').subscribe(res => {
      let postTitle = res.title;
      console.log(postTitle);
    });
  }

}
3
I tried your code and its working at my end. Only problem was that res returns array so it will be res[0].title. - Sujata Chanda
thanks, though I need all the values of title so I guess a for loop is the only way - skydev

3 Answers

1
votes

well, your code has a few problems for one res is of Array type and if you want to access your objects property you'll have to loop through it (perhaps something like this:)

let postTitle = [];
this.http.get<Post>('https://jsonplaceholder.typicode.com/posts').subscribe(res => {
  res.forEach(element => {
  postTitle.push(element);
});
  console.log(postTitle);
});

and I strongly recommend to call an API via a service don't do it in a component.

1
votes

So I tried to replicate this with https://stackblitz.com/edit/angular-njzmwr

I found an issue that, your current api is returning data as an array so either selects the data by the filter from array or something else. pls check the above-mentioned URL

0
votes

The API returns and Array of PostS. Try:

getData() {
  this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts').subscribe(res => {
    let postTitle = res[0].title;
    console.log(postTitle);
  });
}

HTH