2017-08-19 133 views
1

读取以.json文件中的数据我有资产JSON文件文件夹,名为data.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); 
} 

但在这里.detailsdata我没有得到任何东西。

并在此之后我想显示sales_amountcollection_amountHTML文件。

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

在地方的销售金额我要显示的值 如何做到这一点。 我很新的typescript.can任何人请帮助我这一点。

回答

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); 
     }) 
    } 
+0

感谢您response.Actually我试图为u建议(

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

)。 但我没有得到任何结果。 和下面的代码我没有得到任何结果在控制台。 ngOnInit(){ this.myService.getResponseData()。then(response => this.detailsdata = response); cosole.log('result'+ this.detailsdata) }。 所以我怀疑这是否正确。请给我这个告诉我。 – ananya

+0

你能否把{{detailsdata | json}},并检查它是否显示任何内容。需要检查数据是否从JSON文件中实际读取。 –

+0

@ananya您的控制台将不会打印任何内容,因为获取数据的过程将异步运行,并且即使在从服务获取结果之前,仍会执行代码(console.log)。检查我的更新后的代码,只有在提取值后才会记录。 –