How to send a POST request to OData v4 ActionImport with SAPUI5

Viewed 605

I would like to send a POST request to an OData v4 ActionImport. How can I achieve this in an SAPUI5 environment? I had a look at the v4 ODataModel and ODataContextBinding. There are methods for execute an ActionImport but i dont know how to set the body then.

Generally asking: How should I submit OData requests that should not necessarily be bound to the UI? For example, if I just want to query a value from the backend or send a file to the backend. Right now, I create an ODataContextBinding and call the execute/requestObject method but i think that this might not be the best approach (Also i cant set the request body this way). Maybe it might be better to make a direct ajax request?

Thanks in advance!

1 Answers

I stumbled on your question because I had the exact same problem. I'm providing my solution in case it helps someone else.

onValidate: function(oEvent) {
   var oModel = this.getModel("reportService");
   var oActivityCreateContext = this.getCreateContext();
   var oActionODataContextBinding = oModel.bindContext("/validateActivity(...)");
   oActionODataContextBinding.setParameter("activity", oActivityCreateContext.getObject())
   oActionODataContextBinding.execute().then(
      function() {
          var oActionContext = oActionODataContextBinding.getBoundContext();
          console.table(oActionContext.getObject().value);
      }.bind(this)
   );
}

The model "reportService" is a sap.ui.model.odata.v4.ODataModel. The function call is unbound and is declared this way in my service.cds file:

action validateActivity(activity : Activities) returns many rm.ValidationMessage;

The oActionContext.getObject().value contains the response to my function call.

The key here is the setParameter that sets the activity on the payload. Here's what the resulting request could look like:

POST http://localhost:8080/api/ReportService/validateActivity
Content-Type: application/json

{"activity": {
    "activityNumber": 1,
    "report_ID": "a3558fce-76bc-49a9-ae23-bd5566fb3bc6",
    "job_code": "160",
    "learningPeriod": 1,
    "salaryAnnex": "D3",
    "workingRegion_code": "08",
    "unionName": "CSD",
    "local": "Local 123",
    "nbWeeksWorked": 8,
    "nbHourSimple": 110,
    "nbHourTimeAndHalf": 5,
    "nbHourDouble": 0,
    "sin": "111222333",
}}

I hope this will help others who are struggling to do this.

Regards

Related