1

I'm new to Angular 4, and don't really get how to fetch data yet. I've used the Tour of Heroes tutorial to learn it, but now I want to get real data from a JSON file, I'm getting an error:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Here is my code:

  private url = 'data/articles.json';

  constructor(private http: Http) { 
    this.headers = new Headers({ 'Content-Type': 'application/json' });
    this.options = new RequestOptions({ headers: this.headers });
  }

  /**
   * fetch a list of articles
   */
  getArticles(): Promise<Article[]> {
    return this.http.get(this.url, this.options)
               .toPromise()
               .then(response => response.json() as Article[])
               .catch(this.handleError);
  }

I'm simply iterating over the result of getArticles() in an ngFor to output each one.

Here's the code that consumes the service:

this.articleService.getArticles().then(articles => this.articles = articles);
simon_www
  • 489
  • 2
  • 5
  • 13
  • 1
    can you post your json and html – Sajeetharan Oct 30 '17 at 02:08
  • 1
    Your ngFor is probably pointing to an object, not an array. – Matt Searles Oct 30 '17 at 02:11
  • 1
    ^ which would mean the Articles JSON is probably an object, and not a straight array as what you are assuming it to be when you cast it as an `Article[]`. – Michael Fedora Oct 30 '17 at 02:12
  • ^ yep. Try this.articleService.getArticles().then(articles => { this.articles = articles; console.log(articles); }); – Matt Searles Oct 30 '17 at 02:13
  • Also: if using angular CLI you have to configure your data folder or just place your .json file into the src\assets folder. – Alic W Oct 30 '17 at 03:37
  • How does your incoming data look like, could you copy paste the JSON response to your question? – AT82 Oct 30 '17 at 06:35
  • Oh my, I feel silly. That was exactly it. It was late I didn't even think that was the issue. I'd seen a lot of posts saying its a misleading error so was chasing a wild goose on this one. Thanks everyone :) – simon_www Oct 30 '17 at 17:19

0 Answers0