【问题标题】:How to read data from .json file in typescript如何从打字稿中的.json文件中读取数据
【发布时间】:2018-01-28 00:47:20
【问题描述】:

我在 assets 文件夹中有一个名为 data.json 的 json 文件

{
    "response": {
        "sales_amount": 0,
        "collection_amount": 0,
        "carts_amount": 736.63,

}
}

我这样做是为了在 service.ts 文件中获取数据

 my_data: any;
  public getResponseData() : Promise<any> {
      if(typeof(this.my_data) === "undefined") {
            return this.http.get('assets/data.json')
            .toPromise().then(res => {

                                  this.my_data = res.json().response;
                                  return this.my_data;
                }).catch(this.handleError);
      } else {
          return Promise.resolve(this.my_data);
      }


  }

我在 this.my_data 中得到响应,但在 component.ts 文件中我正在这样做

ngOnInit(){


        this.myService.getResponseData().then(response => this.detailsdata = response);
}

但在 this.detailsdata 中,我什么也没得到。

然后我想在 html 文件中显示 sales_amount,collection_amount

<div>
     <span>sales amount</span>
</div>

代替销售额,我想显示价值 这个怎么做。 我对 typescript 很陌生。任何人都可以帮我解决这个问题。

【问题讨论】:

    标签: json typescript


    【解决方案1】:

    您的代码看起来正确。我刚刚在测试应用程序中检查了它。您需要的只是 html 文件中的几行代码。

    请将以下代码添加到您的 html 文件中。

    <p><b>sales amount:</b> {{ detailsdata?.sales_amount }}</p>
    <p><b>collection amount:</b> {{ detailsdata?.collection_amount }}</p>
    <p><b>carts amount:</b> {{ detailsdata?.carts_amount }}</p>
    

    顺便说一句,你的 json 数据是无效的。删除carts_amount 属性后的逗号。

    {
      "response": {
        "sales_amount": 6000.77,
        "collection_amount": 399.57,
        "carts_amount": 736.63
      }
    }
    

    更新:

    ngOnInit(): void {
    
            this.myService.getResponseData().then((value) => {
                //SUCCESS
                console.log(value);
                this.detailsdata = value;
    
            }, (error) => {
                //FAILURE
                console.log(error);
            })
        }
    

    【讨论】:

    • 感谢您的回复。实际上我正在按照您的建议尝试(

      销售额: {{ detailsdata?.sales_amount }}

      )。但我没有得到任何结果。并且使用下面的代码,我在控制台中没有得到任何结果。 ngOnInit(){ this.myService.getResponseData().then(response => this.detailsdata = response); cosole.log('结果'+this.detailsdata) }。所以我怀疑这是否正确。你能告诉我这个吗。
    • 请把{{ detailsdata | json }} 在 html 文件中并检查它是否显示任何内容。需要检查是否真的从 json 文件中读取数据。
    • @ananya 您的控制台不会打印任何内容,因为获取数据的过程将异步运行,并且记录代码 (console.log) 甚至会在从服务获取结果之前执行。检查我更新的代码,它只会在获取值后记录。
    • ,谢谢 Sangram,我正在控制台中获取结果并在 html 中获取数据,也仅使用 {{ detailsdata?.sales_amount }} 这个。我尝试了一个新项目及其工作。可能在当前项目存在一些 css 问题,因此未显示值。非常感谢 Sangram 抽出宝贵时间。 :):)
    猜你喜欢
    • 2019-10-29
    • 2021-08-22
    • 2021-06-28
    • 1970-01-01
    • 2018-12-17
    • 2021-03-21
    • 2020-02-20
    • 1970-01-01
    • 2021-09-26
    相关资源
    最近更新 更多