0

I am currently trying to iterate through an array using *ngFor but nothing shows up on the page. This is the code for the HTML

<ion-header>
  <ion-navbar>
    <ion-title>
      Recent News
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
      <ion-card *ngFor="let article of articles">
        <ion-card-content>
          <h2>{{article.title}}</h2>
          <p>{{article.description}}</p>
        </ion-card-content>
      </ion-card>
</ion-content>

<ion-footer>
  <ion-toolbar>
    <p>Powered by NEWS API</p>
  </ion-toolbar>
</ion-footer>

The following is the code from the .ts (typescript?)

 getNews() {
    this.rest.getNews()
    .then(result => {
      this.news = result;
      console.log(this.news);
    });
  }

The console log of this.news is this. However, if I console.log(this.news.articles[0]), this is the output instead.

Could it be done such that I iterate through from 0 to 9 instead of using ngFor or am I missing something?

EDIT: home.ts as follows

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RestProvider } from '../../providers/rest/rest';

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

  news: any;
  errorMessage: string;


  constructor(public navCtrl: NavController, public rest:RestProvider) {
    this.getNews();
  }

  getNews() {
    this.rest.getNews()
    .then(result => {
      this.news = result;
      console.log(this.news.articles[0]);
    });
  }


}

2 Answers 2

1

Just replace the articles in ngFor with news. The data you want to display is in news array:

<ion-content padding>
      <ion-card *ngFor="let article of news.articles">
        <ion-card-content>
          <h2>{{article.title}}</h2>
          <p>{{article.description}}</p>
        </ion-card-content>
      </ion-card>
</ion-content>
Sign up to request clarification or add additional context in comments.

4 Comments

I get this error after doing this ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
It gives this error ERROR TypeError: Cannot read property 'article' of undefined.
@ZivOfir articles not article
I'm guessing it don't work due to my variable news being any. I edited the OP to include the whole home.ts, could you help me see if I did anything wrong there?
0

Take another variable called articels

  getNews() {
    this.rest.getNews()
    .then(result => {
      this.news = result;
      this.articels = this.news.articles;
      console.log(this.news);
      console.log(this.articels);
    });
  }

with this your html should work fine.

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.