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);
7
  • 1
    can you post your json and html Commented Oct 30, 2017 at 2:08
  • 1
    Your ngFor is probably pointing to an object, not an array. Commented Oct 30, 2017 at 2: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[]. Commented Oct 30, 2017 at 2:12
  • ^ yep. Try this.articleService.getArticles().then(articles => { this.articles = articles; console.log(articles); }); Commented Oct 30, 2017 at 2:13
  • Also: if using angular CLI you have to configure your data folder or just place your .json file into the src\assets folder. Commented Oct 30, 2017 at 3:37

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.