【问题标题】:Iterating through an array in Angular Ionic遍历Angular Ionic中的数组
【发布时间】:2018-08-05 14:28:12
【问题描述】:

我目前正在尝试使用 *ngFor 遍历数组,但页面上没有显示任何内容。这是 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>

以下是 .ts 中的代码(打字稿?)

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

this.news 的控制台日志为this。但是,如果我console.log(this.news.articles[0])this is the output instead

是否可以这样我从 0 迭代到 9 而不是使用 ngFor 或者我错过了什么?

编辑: home.ts如下

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


}

【问题讨论】:

    标签: angular ionic-framework


    【解决方案1】:

    只需将ngFor 中的文章替换为新闻即可。要显示的数据在 news 数组中:

    <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>
    

    【讨论】:

    • 执行此操作后出现此错误ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
    • 它给出了这个错误ERROR TypeError: Cannot read property 'article' of undefined
    • @ZivOfir 文章不是文章
    • 我猜它不起作用,因为我的可变新闻是any。我编辑了 OP 以包含整个 home.ts,你能帮我看看我在那里做错了吗?
    【解决方案2】:

    取另一个名为articels的变量

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

    有了这个,你的 html 应该可以正常工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 2018-06-17
      • 2017-11-20
      • 1970-01-01
      • 2020-01-18
      • 2021-02-11
      • 2018-10-18
      相关资源
      最近更新 更多