Angularjs和Web服务问题

时间:2015-08-11 13:11:40

标签: angularjs web-services

我没有使用$ http.get方法从angular.com中的Web服务响应中获取数据。这是什么原因?它直接转到错误部分。

网络服务代码:

 @GET
 @Path("/getEmployeeList")
 @Produces(MediaType.APPLICATION_JSON)
 public Response getEmployeeList() {
    ArrayList<Employee> empList = (ArrayList<Employee>) employeeService.getAllEmployees();
    return Response.status(200).entity(empList).build();
}

Angular Js:

<script src="angular.js"></script>
</head>
<body  >

<div  ng-app="hello">
    <h1>Greeting</h1>
    <div ng-controller="home" >
      <div ng-repeat="a in greeting">
        <p>The Id is: {{a.empId}}</p>
        <p>The content is: {{a.firstName}}</p>
         <p>The content is: {{a.lastName}}</p>
       </div>
    </div>
 </div>
    </body>
  <script >
   var myApp = angular.module('hello', []);
  myApp.controller('home',['$scope','$http',function($scope,$http) {
    $http.get("http://localhost:8080/restful-jersey-spring-demo/restws/employee/getEmployeeList")
    .success(function(data) {

        $scope.greeting = data;
    }).error(function(data, status, headers, config){
      alert("Error") 
    });
 }]);

</script>

</body>

Json Data From Web services:      网址:http://localhost:8080/restful-jersey-spring-demo/restws/employee/getEmployeeList

 [
{
    "empId": 1,
    "firstName": "Chirag",
    "lastName": "L"
},
{
    "empId": 2,
    "firstName": "Prashant",
    "lastName": "K"
}
]

2 个答案:

答案 0 :(得分:1)

$ http不传递响应数据,而是传递成功回调的响应。 因此使用:

$http.get("http://localhost:8080/restful-jersey-spring-demo/restws/employee/getEmployeeList")
    .success(function(response) {
        $scope.greeting = response.data;
    }).error(function(response){
        alert("Error") 
});

对于CORS错误,请参阅此thread

答案 1 :(得分:1)

在回复中添加标题....

@GET
@Path("/getEmployeeList")
@Produces(MediaType.APPLICATION_JSON)
 public Response getEmployeeList() {
 ArrayList<Employee> empList = (ArrayList<Employee>)  employeeService.getAllEmployees();
 return Response.status(200).entity(empList).***header("Access-Control-Allow-Origin", "*")***.build();
}