【问题标题】:Iteration of json file in typescript in angular?以角度迭代打字稿中的json文件?
【发布时间】:2020-10-04 01:33:14
【问题描述】:
[
        {
            "title": "Marker 1",
            "innercontent": "the Porcelain Factory"
        },
        {

            "title": "Marker 2",
            "innercontent": "The Taj Mahal "

        },
        {
            "title": "Marker 3",
            "innercontent": "Golconda Fort"
        }
]

以上是我的json文件。

<div *ngFor="let marker of currentmrkr">
      <div>
        {{ marker.title }}
      </div>
      <div>
        {{ marker.innercontent }}
      </div>
    </div>

以上是我的html文件。

import * as content from './content.json';
marker.addListener("click", () => {for(let item of content){
            if(marker.getTitle() == item.title){
              this.currentmrkr = item;
            }
          }
}

以上内容在我的打字稿文件中。

这显示了一个错误,例如 -

 core.js:6260 ERROR TypeError: _content_json__WEBPACK_IMPORTED_MODULE_1___namespace is not iterable

我们如何在angular中遍历typescript文件中的json对象以及如何将文件导入typescript?

【问题讨论】:

  • 你像在 js 中一样迭代。通过使用一些for 循环或forEach
  • 是的。迭代后我应该把值放在哪里,以便我可以在 ngfor 中访问它们,因为 ngfor 用于数组而不是对象。
  • 它是一个对象数组。

标签: json angular typescript


【解决方案1】:

如果您想在 Typescript 逻辑中迭代 JSON 以将数据推送到 Firebase,您可以使用名为 Lodash 的库

import * as _ from 'lodash';

myfunction(json) {
    return new Promise((resolve) => {
      _.map(json, (e, i) => {
       _.keys(e).map(() => {
        this.afs.collection('library').doc('doc ' + i).set(e);
       })
      })
     resolve();
   })
  }

如果您需要更多详细信息,我有一个完整的blog。否则,如果您在 typescript 中定义了一个简单的 json 对象并希望在 HTML 中查看特定值,则可以使用以下方法:

import { Component } from "@angular/core";

@Component({
  selector: "app-some-section",
  templateUrl: "./some-section.component.html",
  styleUrls: ["./some-section.component.scss"],
})
export class SomeSectionComponent {
  users = [
    {
      name: "Jacob",
      job: "Analyst",
      city: "California",
    },
    {
      name: "John",
      job: "Founder",
      city: "New York",
    },
  ];

  constructor() {}

}

然后在 HTML 模板中:

<div class="card" *ngFor="let user of users">
    <h3 class="job">{{ user.job }}</h3>
    <h3 class="name">{{ user.name }}</h3>
    <h3 class="city">{{ user.city }}</h3>
</div>

【讨论】:

  • 感谢您的 loadash 逻辑很棒。但我收到一个错误,你也可以看到错误。
  • 谢谢@angularnoob,你能分享一下你的错误细节吗?也许我可以帮忙。
猜你喜欢
  • 2019-01-30
  • 2020-10-25
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 2020-07-22
  • 2016-02-03
  • 1970-01-01
  • 2022-06-30
相关资源
最近更新 更多