CodeWorld
CodeWorld

Reputation: 2307

Send two parameters from angular UI in post method and handled by java API

Just need guidance... From controller to service, variables are accessible. But not available when they are send to api side. (With one variable it's working perfectly fine) The variable values are coming after some calculations.

Service.js code...

function MySvcFunction(value1, value2) {
    console.log('value1 : ', value1);  //printing value1
    console.log('value2 : ', value2);  //printing value2
    return $http.post('http://' + api_url + value1, value2).then(
         function (response) {
              //manage success
         },
         function (error) {
              //manage error;
         });
}

Controller.js code...

$scope.someFunction = function(){
    console.log('value1 : ', value1);  //printing value1
    console.log('value2 : ', value2);  //printing value2
  MySvcController.MySvcFunction($scope.value1, $scope.value2).then(
  function (response) {
     //display on screen 
 });

And now api code in java...

Scenario-1 exception (with two @RequestBody)

@PostMapping(value = "/api_url")
public ResponseEntity<Object> MyFunction(@RequestBody Integer value1, @RequestBody Integer value2) {
    System.out.println("value1 : "+ value1);
    System.out.println("value2 : "+ value2);        
}
//Exception:
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Stream closed; nested exception is java.io.IOException*/

Scenario-2 exception (with one @RequestBody)

@PostMapping(value = "/api_url")
public ResponseEntity<Object> MyFunction(@RequestBody Integer value1, Integer value2) {
    System.out.println("value1 : "+ value1);   //value1 : int val
    System.out.println("value2 : "+ value2);   //value2 : null
}
//Exception:
nested NullPointerException with root cause.

Upvotes: 0

Views: 1311

Answers (1)

CodeWorld
CodeWorld

Reputation: 2307

I got it working not sure whether right or not?

Controller.js

$scope.someFunction = function(){
  var bothVar = {'value1': $scope.value1, 'value2': $scope.value2};
  MySvcController.MySvcFunction(bothVar).then(
    function (response) {
      //display on screen 
});

Service.js

function MySvcFunction(bothVar) {
 return $http.post('http://' + api_url + bothVar).then(
     function (response) {
          //manage success
     },
     function (error) {
          //manage error;
     });
}

API side java code

@PostMapping(value = "/api_url")
public ResponseEntity<Object> suggestBreakfast(@RequestBody Map bothVar){
    System.out.println("value1 is : "+ bothVar.get("value1"));
    System.out.println("value2 is : "+ bothVar.get("value2"));
}
// And i am getting those two values here successfully

Upvotes: 1

Related Questions