简体   繁体   English

如何访问角度组件中的 json 对象数组

[英]How to access the array of json objects in angular component

I have the below data from api call:我有来自 api 调用的以下数据:

how to bind this data to component.html page in angular.如何将此数据绑定到 angular 的 component.html 页面。 even with NgFor loop also fine即使使用 NgFor 循环也很好

[
    {
        "newsCategory": "Corporate",
        "newsHead": "header data",
        "newsDate": "20-01-2020",
        "newsContent": "something comkdnf"
    },
  {
        "newsCategory": "hjhds",
        "newsHead": "hjkhbksd",
        "newsDate": "20-01-2020",
        "newsContent": "jhvjchddnf"
    },
]

My code:我的代码:

///// Some elements are there in html.
<div>{{news[0].newsDate}}</div>
<div>{{news[0].newsCategory}}</div>
<div>{{news[0].newsHead}}</div>
constructor(public _newsService : NewsService) { }
newsdetails:allNewsArray[]

ngOnInit(): void {
this._newsService.getNews().subscribe(
       (news : allNewsArray[])=>{console.log(typeof(newsdetails[0]))}
);}


export class allNewsArray {​​​​​​​​
newsCategory: string;
newsHead: string;
newsDate: string;
newsContent: string;
}​​​​​​​​

in console log value is coming.. but not able to bind it in the component html在控制台日志值即将到来..但无法在组件 html 中绑定它

You are currently not binding your data from your .subscribe() to your variable in your class.您目前没有将.subscribe()数据绑定到您.subscribe()中的变量。 The following will fix your issues:以下将解决您的问题:

HTML

<div *ngFor="let news of newsdetails">
  <div>{{ news.newsDate }}</div>
  <div>{{ news.newsCategory }}</div>
  <div>{{ news.newsHead }}</div>
</div>
COMPONENT

newsdetails: allNewsArray[];

ngOnInit(): void {
  this._newsService.getNews().subscribe(
    (news: allNewsArray[]) => this.newsdetails = news
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM