[英]How to read data from .json file in typescript
I have a json file in assets folder called data.json 我在assets文件夹中有一个名为data.json的json文件
{
"response": {
"sales_amount": 0,
"collection_amount": 0,
"carts_amount": 736.63,
}
}
I am doing like this to get data in service.ts file 我这样做是为了获取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);
}
}
Here i am getting response in this.my_data,but in the component.ts file i am doing like this 在这里我得到了this.my_data的响应,但在component.ts文件中,我这样做
ngOnInit(){
this.myService.getResponseData().then(response => this.detailsdata = response);
}
but here in this.detailsdata i am not getting anything. 但在这里.detailsdata我没有得到任何东西。
and after this i want to display sales_amount , collection_amount in the html file. 在此之后我想在html文件中显示sales_amount , collection_amount 。
<div>
<span>sales amount</span>
</div>
In place of sales amount i want to display the value how to do this. 代替销售额,我想显示值如何做到这一点。 I am very new to typescript.can anyone please help me with this.
我是打字稿的新手。任何人都可以帮助我。
Your code looks correct. 您的代码看起来正确。 I just checked that in test application.
我刚刚在测试应用程序中检查过 What you need is just few lines of code in html file.
你需要的只是html文件中的几行代码。
Please add following code to your html file. 请将以下代码添加到您的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>
By the way, your json data is invalid. 顺便说一下,你的json数据无效。 Remove comma after the
carts_amount
property. 在
carts_amount
属性后删除逗号。
{
"response": {
"sales_amount": 6000.77,
"collection_amount": 399.57,
"carts_amount": 736.63
}
}
Updates: 更新:
ngOnInit(): void {
this.myService.getResponseData().then((value) => {
//SUCCESS
console.log(value);
this.detailsdata = value;
}, (error) => {
//FAILURE
console.log(error);
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.