[英]Parsing JSON to display the data in angular
因此,我將數據存儲在數據庫中,並在 angular 中提取數據,問題是當我嘗試顯示數據時出現以下錯誤。 我只需要使用ngFor * 在 html 中顯示問題。我對 angular 完全陌生,任何指導都會非常有幫助。
this.selfHelpService.getFgSelfHelpByName("BYOD").subscribe(data => {
// console.log(data);
const BYOD = JSON.parse(data["data"]);
// console.log(BYOD );
});
<div class="cards" *ngFor="let BYOD of BYOD">
<div class="read-1">
{{BYOD.posts.question}}
</div>
</div>
由於您正在獲取數據,因此您可以執行以下操作:
// If this is your response:
{"BYOD":[ ` { "posts": [ {"Question":"BYOD (Android)","answer":"???"}, {"Question":"BYOD (IOS)","answer":"?????"} ] } ] };
this.selfHelpService.getFgSelfHelpByName("BYOD").subscribe(data => {
try {
const BYOD = JSON.parse(JSON.stringify(data["data"]));
} catch(err) {
console.log('Try catch error ==>', err);
}
// Declare a variable in the component.ts above constructor called byodPostsData
// Assign the values to that variable
this.byodPostsData = BYOD[0].posts;
});
// In your HTML now, simply loop through the this.byodPostsData;
<div class="cards" *ngFor="let eachPost of byodPostsData">
<div class="read-1" *ngIf="eachPost && eachPost.question">
{{ eachPost.question }}
</div>
</div>
我不確定您要循環什么,但是,如果您想循環 byod,
<div class="cards" *ngFor="let byod of byod.BYOD[0].posts">
<div class="read-1">
{{byod.Question}}
</div>
</div>
除了在您的示例代碼中,byod 是 function 中的本地 scope,您應該從中創建一個組件變量,以使其可由 HTML 訪問。
隨意詢問是否有不清楚的地方。
由於您是 Angular 的新手:這就是決定訪問響應的方式:
0 應該來自這樣一個事實,即響應是 JSON object 和 JSON 鍵 BYOD,它指示 BYOD 的數組作為值:所以 BYOD [0] 的第一個項目是另一個 object 帶有 JSON 鍵“posts”,“posts”的值是您要循環的數組。 如果您將請求中的數據解析為名為 byot 的組件屬性,它應該可以在 html 中訪問,如下所示: byod.BYOD[0].posts 我希望我說得更清楚一點。
這是一個堆棧閃電戰!
https://stackblitz.com/edit/angular-ivy-jcxgfo?file=src/app/app.component.ts
正如這里其他評論員之前提到的:我不確定你為什么使用JSON.parse()
。 但是,如果您確實應該使用它,請嘗試使用它:
// Generally its considered good practice to use try-catch for JSON.parse() for data
try {
const BYOD = JSON.parse(JSON.stringify(data["data"]));
} catch(err) {
console.log('Try catch error ==>', err);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.