在post方法中从angular UI发送两个参数,并由java API处理

时间:2017-08-08 07:01:37

标签: java angularjs spring-mvc

只需要指导...... 从控制器到服务,可以访问变量。但是当他们被发送到api方面时不可用。 (有一个变量,它工作得非常好) 变量值在一些计算之后出现。

Service.js代码......

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代码......

$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 
 });

现在java中的api代码...

Scenario-1异常(有两个@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*/

场景-2异常(使用一个@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.

1 个答案:

答案 0 :(得分:1)

我不确定是否正确?

Controller.js

composer update --no-scripts 
composer update

Service.js

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

API端java代码

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