简体   繁体   中英

How to read data from .json file in typescript

I have a json file in assets folder called data.json

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

}
}

I am doing like this to get data in service.ts file

 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

ngOnInit(){


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

but here in this.detailsdata i am not getting anything.

and after this i want to display sales_amount , collection_amount in the html file.

<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.

Please add following code to your html file.

<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. Remove comma after the carts_amount property.

{
  "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);
        })
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM