【问题标题】:Iterating over an array of objects to create a post-listing遍历对象数组以创建后列表
【发布时间】:2018-04-12 09:47:40
【问题描述】:

这里是新手

const posts=[{icon: 'heart',
              color: 'teal',
              category: 'Lifestyle',
              title: 'This is title of the news',
              img: 'https://bbb.com/img38.jpg',
              content: `Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo
              minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor.`,
              by: 'Jessica Clark',
              date: '26/08/2016',
  }, ...]

我有一个这些帖子对象的数组,我想从中创建一个实际的帖子列表。

  1. 数组应该放在哪里?首先我已经输入了 constructor() 方法,但现在我得到了建议,它应该进入 ngOnInit()。

  2. 我应该为此使用 ng-repeat,如果是,我应该如何访问 constructor()/ngOnInit() 中的内容?

我在摆弄

<div class="row" ng-repeat="post in this.posts">
    <img src="{{post.img}}" alt="First sample image">
    <h6 class="pb-1"><i class="{{post.icon}}"></i> {{post.category}}</h6>
    <h4 class="mb-4"><strong>{{post.title}}</strong></h4>
    <p>{{post.content}}</p>
    <p>by <a>{{post.title}}</strong></a>,{{post.date}}</p>
</div>

但显然它并没有带来成功。

【问题讨论】:

  • ng-repeat 是 angularjs 而 constructor()/ngOnInit() 是 angular。你使用哪个版本的 Angular/AngularJs?
  • Angular 4.3.6 Angular Cli 1.4.9
  • 这样使用&lt;div class="row" *ngFor="let post of posts"&gt;&lt;/div&gt;
  • 所以你应该使用*ngFor="let post of posts" 而不是ng-repeat="post in this.posts"
  • 你仍然在你的 plunker 中混合 angular 和 angularjs。 Angular 没有很好地初始化,所以你的页面中有 {{...}}。请提交一个有效的 plunker。

标签: javascript html arrays angular object


【解决方案1】:

事实证明我的代码在几个方面存在缺陷。纠正它们使我得到了预期的结果-让我将它们包括在这里,以便其他人可以参考。

  1. 可以在组件内部“按原样”提供要插入的对象的数组,并使其public 使其可访问 - 如下所示:

    公开帖子:对象[] = [ { 图标:'fa fa-heart', ...},{...}];

  2. ng-repeat 是一个糟糕的想法,因为我对自己实际在做什么缺乏专业知识。正确的方法是*ngFor="let post in posts"。其他一切都很好。

还是谢谢

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 2016-01-12
    • 2020-07-18
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多