Search code examples
mysqlangularrestspring-data-jpastring-interpolation

Interpolate an object from rest API


hello I'm having trouble on how to interpolate the object from rest API, I can see the objects in console log but I can't bind it in a label to my table

this is the object I want to interpolate in my table

clerk: name: "May Anne" [[Prototype]]: Object

this is my service.ts

//fetch discounte Bill
  fetchDiscountedBill(): Observable<any>{
    return this.http.get(this.baseUrl + '/discountedBill');
  }

this is the model.ts

 export class BillingModel{
        clerk : {
            name: string;
        }
    }

I call the model.ts to my table.component.ts with this

billingModel: BillingModel = {
      clerk: {
        name: ''
      }
    };

and create a method with this

 getDiscountedBill(){
        this.dataStorageService.fetchDiscountedBill().subscribe(resp => {
          console.log(resp)
          this.billingModel = data;;
        }, err => {
          console.log(err)
        });
      }

and this is the label I want to interpolate or bind the object

<tr>
        <td colspan="4">Attending Clerk: </td>
    </tr>

Please help thank you!


Solution

  • In your ts file within subscribe, you can assign the value as:

    this.billingModel.clerk = resp.clerk;
    

    and then display the clerk name within your html template using interpolation as:

    {{billingModel?.clerk?.name}}
    

    If your HTTP response data structure matches your defined model, then you can use the same type in your service class method as:

    fetchDiscountedBill(): Observable<BillingModel> {
        return this.http.get<BillingModel>(this.baseUrl + '/discountedBill');
    }
    

    and within subscribe you can simply do:

    this.billingModel = resp;
    

    Also when defining your model, you don't need to define it as a class, but can define it as an interface:

    export interface BillingModel {
        clerk: {
            name: string;
        }
    }