亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

*ngFor 循環無法在 Angular 9 中顯示 json 數據

*ngFor 循環無法在 Angular 9 中顯示 json 數據

翻閱古今 2023-07-14 16:49:22
我正在 Angular 9 應用程序中讀取本地 json 文件,并嘗試將結果顯示到 app.component.html。我在這里花了相當多的時間研究和嘗試不同的技術,例如 *ngFor 循環訪問 httpClient.get 調用返回的數據(存儲在變量中),以及使用技術將數據集 this.initialData轉換為數組對象數組,存儲在this.dataValues變量中。我在每次循環嘗試后發布了屏幕截圖,替換了變量。我將不勝感激任何關于如何實現這一點的反饋,到目前為止,數據不會呈現到頁面,而是向我將發布的控制臺拋出錯誤。我可以 =use console.log() 來查看變量是用 JSON 數據填充的。這是 json 文件:{  "data": [    {      "id": 18,      "internal_name": "scone_birthday",      "type": "coupon",      "description": "Free Scone awarded for a members birthday",      "heading": "Toast to your birthday!",      "subheading": "Our gift to you",      "body": "This is the body for the <span style='font-family: \"Times New Roman\", Times, serif;'><strong><em><span style=\"color: rgb(0, 198, 255);\">birthday offer.</span></em></strong></span><span style=\"font-family: Georgia,serif;\"></span>",      "subject": "",      "details": "This is the details for the birthday <strong>offer</strong>.",      "action": "",      "image1_bg": "",      "image_url": "images/birthday_candle.png",      "respondable": true,      "metric_amount": "150.0",      "metric_name": "spend",      "usage_end_date": "2020-11-05T23:59:59.000+11:00"    },    {      "id": 4,      "internal_name": "voucher",      "type": "coupon",      "description": null,      "rank": "1.0",      "start_date": null,      "end_date": null,      "heading": "HighFIVE!",      "subheading": "You&#39;ve got $5 of dough*",     }  ]}
查看完整描述

2 回答

?
白衣染霜花

TA貢獻1796條經驗 獲得超10個贊

{

  "data": [

    {

      "id": 18,

      "internal_name": "scone_birthday",

      "type": "coupon",

      "description": "Free Scone awarded for a members birthday",

      "heading": "Toast to your birthday!",

      "subheading": "Our gift to you",

      "body": "This is the body for the <span style='font-family: \"Times New Roman\", Times, serif;'><strong><em><span style=\"color: rgb(0, 198, 255);\">birthday offer.</span></em></strong></span><span style=\"font-family: Georgia,serif;\"></span>",

      "subject": "",

      "details": "This is the details for the birthday <strong>offer</strong>.",

      "action": "",

      "image1_bg": "",

      "image_url": "images/birthday_candle.png",

      "respondable": true,

      "metric_amount": "150.0",

      "metric_name": "spend",

      "usage_end_date": "2020-11-05T23:59:59.000+11:00"

    },

    {

      "id": 4,

      "internal_name": "voucher",

      "type": "coupon",

      "description": null,

      "rank": "1.0",

      "start_date": null,

      "end_date": null,

      "heading": "HighFIVE!",

      "subheading": "You&#39;ve got $5 of dough*",

      "body": "Redeem for a $5 reward. <a href=\"https://en.wikipedia.org/wiki/Lorem_ipsum\" rel=\"noopener noreferrer\" target=\"_blank\">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",

      "subject": "Subject",

      "details": "",

      "action": "",

      "image1_bg": "",

      "image_url": "images/five_dollar.png",

      "respondable": true,

      "metric_amount": "200.0",

      "metric_name": "point",

      "usage_end_date": "2020-11-08T23:59:59.000+11:00"

    },

    {

      "id": 19,

      "internal_name": "loaf_welcome",

      "type": "coupon",

      "description": "Onboarding offer for member - free loaf ",

      "start_date": null,

      "end_date": null,

      "heading": "Get a slice of delight",

      "subheading": "Treat Yourself",

      "body": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",

      "subject": "",

      "details": "",

      "action": "",

      "image1_bg": "",

      "image_url": "images/gift.png",

      "respondable": true,

      "metric_amount": "100.0",

      "metric_name": "spend",

      "usage_end_date": "2020-12-30T23:59:59.000+11:00"

    }

  ]

}


查看完整回答
反對 回復 2023-07-14
?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

不完全確定您要做什么,但似乎數組實際上位于嵌套屬性內data。您可以Array#map僅提取特定屬性并async在模板中使用管道來避免訂閱。


嘗試以下操作


控制器


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


import { Observable } from "rxjs";

import { map } from "rxjs/operators";


@Component({ ... })

export class HomeComponent implements OnInit {

  dataValues$: Observable<any>;


  constructor(private dataService: DataService) {}


  ngOnInit() {

    this.dataValues$ = this.http.get('assets/rewards.json')

      .getRewards()

      .pipe(

        map((data: any) => (data.data as Array<any>).map((d: any) => d.body))

      );

  }

}

模板


<ng-container *ngIf="(dataValues$ | async) as dataValues">

    <table class="table table-striped">

        <thead>

            <tr>

                <td>Data Values 1</td>

                <td>Data Values 2</td>

                <td>Data Values 3</td>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td *ngFor="let column of dataValues">

                    <span [innerHTML]="column | safeHtml"></span>

                </td>

            </tr>

        </tbody>

    </table>

</ng-container>

安全管


import { Pipe, PipeTransform } from "@angular/core";

import { DomSanitizer } from "@angular/platform-browser";


@Pipe({ name: "safeHtml", pure: true })

export class SafePipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) {}


  transform(value: string): any {

    return this.sanitizer.bypassSecurityTrustHtml(value);

  }

}

工作示例:Stackblitz

更新:迭代控制器中的數組

要在控制器中使用響應,您可以跳過async管道并在控制器中訂閱。


嘗試以下操作


export class HomeComponent implements OnInit {

  constructor(private dataService: DataService) {}


  ngOnInit() {

    this.dataService.getRewards().subscribe({

      next: (data: any) => {

        data.data.forEach((item: any) => {

          console.log(item);

          console.log("id:", item.id);

          console.log("internal_name:", item.internal_name);

          // do something else

        });

      }

    });

  }

}

工作示例:Stackblitz


查看完整回答
反對 回復 2023-07-14
  • 2 回答
  • 0 關注
  • 169 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號