简体   繁体   中英

How to access the array of json objects in angular component

I have the below data from api call:

how to bind this data to component.html page in angular. even with NgFor loop also fine

[
    {
        "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

You are currently not binding your data from your .subscribe() to your variable in your class. 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
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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