为了账号安全,请及时绑定邮箱和手机立即绑定

*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 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信