簡體   English   中英

如何從typescript中的.json文件中讀取數據

[英]How to read data from .json file in typescript

我在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);
}

但在這里.detailsdata我沒有得到任何東西。

在此之后我想在html文件中顯示sales_amountcollection_amount

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

代替銷售額,我想顯示值如何做到這一點。 我是打字稿的新手。任何人都可以幫助我。

您的代碼看起來正確。 我剛剛在測試應用程序中檢查過 你需要的只是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);
        })
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM