簡體   English   中英

如何訪問角度組件中的 json 對象數組

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

我有來自 api 調用的以下數據:

如何將此數據綁定到 angular 的 component.html 頁面。 即使使用 NgFor 循環也很好

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

我的代碼:

///// 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;
}​​​​​​​​

在控制台日志值即將到來..但無法在組件 html 中綁定它

您目前沒有將.subscribe()數據綁定到您.subscribe()中的變量。 以下將解決您的問題:

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