2017-12-26 18 views
1

マイサービス角度のHTTP POSTは、複雑なオブジェクトを送信

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, 
      }; 
     }) 
    ] 
... 
}; 

このループdoesntのはbookingItem.SubUnitsで配列を埋めます。 Array.forEachは値を返しません。それ以外に、変数unitsは使用されません。代わりにArray.mapを使用して新しい配列を作成することができます。

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

これは、1つの配列要素がcreateBooking.booking.relatedVechilesからなる配列を作成します。それがあなたのために起こっているかどうかはわかりませんが、それはあなたの仕事の中にあります。

+0

別の方法では、foreach単位が割り当てられました。しかし、あなたの 'マップ'は正常に動作しています。どうもありがとう。 – Eldho

1

JSON.stringifyを使用しようとしましたか?ただ、使用:

SubUnits :unitsArray; 
関連する問題