简体   繁体   中英

Assign promise to Interface in Angular 7

I'm trying to get the value's from a object in Angular 7.

I'm receiving the data from the following http get call in the service class:

  async getSelectedRatecard(id: number): Promise<Ratecard> {
      return await this.http.get<Ratecard>('http://localhost:8080//shipmentRate/' + id)
      .toPromise();
  }

So this call returns a promise. I use this promise in the following call:

 setCarrier(id: number){
    this.selectedRatecard = this.ratecardService.getSelectedRatecard(id);
    this.updateCurrentValue();
  }

Right now, the type of selectedRatecard is any:

selectedRatecard: any;

My goal is that selectedRatecard is of type Ratecard, which is an interface:

export interface Ratecard{

    carrierId: number,
    ucarrierName: string,
    customsClearanceCosts: number,
    flegtSurcharge: number,
    hsCodeCharge: number,
    provisionForPrePaidDutiesFactor: number,
     prepaidCustomsDuty: number,
     deliveryOrder: number,
     inspectionCharges: number,
     lsps20feet: number,
     lsps40feet: number,
     lastmileCtvrede: number,
     ocmFee: number
   

}

The reason i want to do this is because right now I can not annotate with for example this.selectedRatecard[carrierId] . This will get me undefined printed.

When I console.log(this.selectedRatecard) the following is printed:

ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
__zone_symbol__state: true
__zone_symbol__value:
carrierId: 3
carrierName: "Hapag-Lloyd Rotterdam"
customsClearanceCosts: 68
deliveryOrder: 40
flegtSurcharge: 55
hsCodeCharge: null
inspectionCharges: 15
lastmileCtvrede: 94
lsps20feet: 15
lsps40feet: 15
ocmFee: 100
prepaidCustomsDuty: null
provisionForPrePaidDutiesFactor: null
__proto__: Object
__proto__: Object

But I want this printed in the following way so I can acces values in the object. This is wat gets returned by the http get call in Postman:

{
    "carrierId": 3,
    "carrierName": "Hapag-Lloyd Rotterdam",
    "customsClearanceCosts": 68.0,
    "flegtSurcharge": 55.0,
    "hsCodeCharge": null,
    "provisionForPrePaidDutiesFactor": null,
    "prepaidCustomsDuty": null,
    "deliveryOrder": 40.0,
    "inspectionCharges": 15.0,
    "lsps20feet": 15.0,
    "lsps40feet": 15.0,
    "lastmileCtvrede": 94.0,
    "ocmFee": 100.0
}

You have two options-

Option 1 (Using .then callback)

setCarrier(id: number) {
    this.ratecardService.getSelectedRatecard(id).then(data => {
            this.selectedRatecard = data;
            this.updateCurrentValue();
    });
}

Options 2 (Using async-await )

async setCarrier(id: number) {
    this.selectedRatecard = await this.ratecardService.getSelectedRatecard(id);
    this.updateCurrentValue();
}

Improvements

By the way, you don't need async-await in your service method. You can simply return promise-

getSelectedRatecard(id: number): Promise<Ratecard> {
    return this.http
            .get<Ratecard>('http://localhost:8080//shipmentRate/' + id)
            .toPromise();
}

Example 1

But if you want to perform some actions before returning it, you can then use async-await -

async getSelectedRatecard(id: number): Promise<Ratecard> {
    const data = await this.http
        .get<Ratecard>('http://localhost:8080//shipmentRate/' + id)
        .toPromise();
    
    // Just an example of some data manipulation before returning
    data.foo = 'bar';
    return data;
}

Example 2

Another example can be something like-

export class Ratecard {

    carrierId: number;
    ucarrierName: string;
    customsClearanceCosts: number;
    flegtSurcharge: number;
    hsCodeCharge: number;
    provisionForPrePaidDutiesFactor: number;
    prepaidCustomsDuty: number;
    deliveryOrder: number;
    inspectionCharges: number;
    lsps20feet: number;
    lsps40feet: number;
    lastmileCtvrede: number;
    ocmFee: number

    foo: string;

    constructor(data?: any) {
        data = data || {};
        this.carrierId = data.carrierId;
        this.ucarrierName = data.ucarrierName;
        // Same for other properties
    }

    doFooBar() {
        this.foo = 'bar';
    }
}
async getSelectedRatecard(id: number): Promise<Ratecard> {
    const data = await this.http
        .get<Ratecard>('http://localhost:8080//shipmentRate/' + id)
        .toPromise();

    const rateCard = new Ratecard(data);
    rateCard.doFooBar();
    return rateCard;
}

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