1

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);
    });
  }

}
2
  • 1
    I tried your code and its working at my end. Only problem was that res returns array so it will be res[0].title. Commented Aug 6, 2018 at 7:31
  • thanks, though I need all the values of title so I guess a for loop is the only way Commented Aug 6, 2018 at 7:35

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, yes i will do that. I just wanted to try an interface in a test call
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.