2017-05-03 50 views
-1

我正在嘗試使用參數創建一個帶有參數的angularjs $ http.get請求,但由於syntaxt可能會導致它不工作。能否請你 確認我在做什麼錯的,也許語法是錯誤的angularjs來電或Java API的方法

$http.get(document.requestPathPrefix + "/home/my-api", 
    $scope.requestParametersObject 
    ).then(
     function(response) { 
      $scope.output = response.data; 
     }, 
     function(response) { 
      $scope.retrieveErrorMssg = "Failed to retrieve required data."; 
    }); 

我的參數是這樣的形象

parameter object for api call

在而在java api中這樣調用

@RequestMapping(value = "/my-api", method = RequestMethod.GET) 
public ResponseEntity<Collection<MyObjectResponse>> getMyObjResponse(@RequestBody final MyObjectRequest request) 
{ 
    Map<Integer,MyObjectResponse> oResponse = new HashMap<>(); 
    try { 

     //Manipulation and db calls 

    } catch (Exception e) { 
     log.error(e.getMessage(), e); 
    } 
    return new ResponseEntity<Collection<MyObjectResponse>>(oResponse.values(), HttpStatus.OK); 
} 
+0

你爲什麼做獲取請求而不是創建發佈請求? –

+0

根據我的理解,我可以在此場景中使用獲取或發佈 – zumuhu

回答

0

如果您擔心語法問題,請查看此簡單示例並根據需要對其進行修改。

在JS,你http.get調用應該包含URL及其參數如有

$http.get('getUserInfo', 
{ 
    params : { 
      'userEmail' : 'userEmail' 
    } 
}).then(function(response) { 
     console.log(response); 
}); 

如果您將參數傳遞給API調用,確保您的Java控制器或服務具有參數定義爲接收相同。理想情況下,參數應呼叫,而供應商

例如,對於上面的API調用,彈簧控制器應低於等之間的匹配,

@RequestMapping(value = "/getUserInfo", method = RequestMethod.GET) 
public @ResponseBody User getUserInfo(
     @RequestParam("userEmail") String userEmail) { 
// Do Something 
} 
+0

我的擔心不僅僅是語法,它只是如果IAM正確傳遞來自http.get請求的參數,我想有一些錯誤的格式,因爲我的Java調用does'nt叫 – zumuhu

+0

是的,因爲你的參數應該與http.get調用相匹配,而不是你的情況,我相信 – CrazyMac

+0

也確保URL是否完全匹配。在你的情況下,你已經在API映射之前添加了/ home。所以,當URL和參數匹配,然後它應該觸發API – CrazyMac

1

嘗試,

$http({ 
       url: '/home/my-api', 
       method: "GET", 
       headers: { 
        'Content-type': 'application/json' 
       }, 
       data: JSON.stringify(request) 
      }).success(function(data, status, headers, config) { 

      }).error(function(data, status, headers, config) { 

       return null; 
     });