1

내 서비스 각 HTTP 포스트는 복잡한 객체를 보낼

public submitBooking(createBooking: CreateBooking) { const body = this.getSaveBookingRequestBody(createBooking); //const json = JSON.Stringify(body) //It throws 415 error return this.httpClient.post(this.baseUrl + 'Save', body) .subscribe(); } private getSaveBookingRequestBody(createBooking: CreateBooking): any { const body = { 'Booking': { 'Header': this.getBookingHeader(createBooking), //It works fine. 'Items': [this.getBookingItems(createBooking)], }, 'TestOnly': !environment.production, }; this.Logger.log(body); return body; } private getBookingItems(createBooking: CreateBooking): any { const bookingItem = { 'CountryOfOrigin': createBooking.booking.countryoforigin, 'VehicleValue': createBooking.booking.valueofvechicle, 'SerialNumber': createBooking.booking.bookingNumber, 'Description': createBooking.booking.description, 'Mobility': createBooking.booking.mobility, 'Currency': createBooking.booking.currency, 'Weight': createBooking.booking.weight, 'Year': createBooking.booking.year, 'Cbm': createBooking.booking.cbm, //This is an array it doesn't work. 'SubUnits':[ createBooking.booking.relatedVehicles.forEach(element => { const units = { 'RelationType': element.relation, 'Weight': element.weight, 'Year': element.year, }; })], }; return bookingItem; 

내가 WEB API의 SubUnits 항상 빈 POST 본문을 만들

. 배열을 루프 처리하고 본문으로 보낼 개체를 만드는 방법.

내 각 모델과 WEB-API 객체 나는 또한 JSON.Stringify(unitsArray) 및 시도했다

다른 소단위

로 돌아
const unitsArray = []; 

createBooking.booking.relatedVehicles.forEach(element => { 
     const units = { 
      'RelationType': element.relation, 
      'SerialNumber': element.chassisno, 
      'Weight': element.weight, 
      'Year': element.year, 
     }; 
     unitsArray.push(units); 
    }); 
SubUnits : JSON.stringify(unitsArray); // It also doesn't work with API. 

버전 : 각도 5 타이프 라이터 2.4. 2

답변

1
const bookingItem = { 
... 
    'SubUnits': [ 
     createBooking.booking.relatedVehicles.forEach(element => { 
      const units = { 
       'RelationType': element.relation, 
       'Weight': element.weight, 
       'Year': element.year, 
      }; 
     }) 
    ] 
... 
}; 

이 루프 나던 bookingItem.SubUnits의 배열을 입력합니다. Array.forEach은 값을 반환하지 않습니다. 그 외에도 변수 units은 절대로 사용되지 않습니다. 대신 할 수있는 일은 Array.map을 사용하여 새 배열을 만드는 것입니다.

'SubUnits': [ 
    createBooking.booking.relatedVehicles.map(element => ({ 
     'RelationType': element.relation, 
     'Weight': element.weight, 
     'Year': element.year 
    })) 
] 

이렇게하면 createBooking.booking.relatedVechiles의 배열 요소 1 개가있는 배열이됩니다. 그게 당신이 가고있는 일인지 확신 할 수 없지만, 그것은 당신의 작전에 있습니다.

+0

foreach 단위는 다른 방법으로 할당되었습니다. 그러나 당신의'map'은 잘 동작합니다. 매우 감사합니다. – Eldho

1

JSON.stringify를 사용하지 않으셨습니까? 그냥 사용

SubUnits :unitsArray;