Ahmed Hassan
Ahmed Hassan

Reputation: 65

how to get object from spring service in angular controller?

the service is working on spring But when i try to call a service in angular , the result object is empty and nothing is returned

service code :

public class CalculatorController {

@CrossOrigin(origins = "http://localhost:8090")
@GetMapping("/calc/{number1}/{number2}")
public Calculator calc(@PathVariable int number1, 
            @PathVariable int number2){
        Calculator c = new Calculator(number1 , number2) ;
    return c;
}

}

controller js code :

angular.module("myApp", [])
.controller("myCtrl", function($scope , $http) {
    	$http.get('http://localhost:8090/calc/5/8').
    	then(function (response)
    			{ $scope.result = response.data; }) ;
    	
    });
    
    
    

html code :

<!DOCTYPE html>
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
		<title>Hello AngularJS</title>
		<script src="moule.js"></script>
</head>

<body ng-app="myApp" ng-controller="myCtrl">
	<div ng-controller="myCtrl">
	<p><span class="add">add is {{ result.add }}</span></p>
	<span class="sub">sub is {{ result.sub }}</span>
	</div>

</body>
</html>

thanks in advance

Upvotes: 1

Views: 200

Answers (2)

Tom
Tom

Reputation: 3850

Your CORS filter (@CrossOrigin) is set to http://localhost:8090 but seems like this is where your server side code reside. CORS should allow a source outside of your server to query your API, that means you need to provide your client side port information.

Lets say your server side runs on 8090 and your client on 8080. Your filter on the server side should allow 8080 to use the API from a browser.

Try to change the CORS filter to match your client side not the server side.

Also, look in chrome debug tools (F12) to see if you have a CORS exception.

More information about CORS:

  1. Cross-origin resource sharing
  2. Understanding CORS
  3. Enabling Cross Origin Requests for a RESTful Web Service

Upvotes: 2

Hadi
Hadi

Reputation: 17299

it should be like this. you forgot add @ResponseBody annotation for your method

@CrossOrigin(origins = "http://localhost:8090")
@GetMapping("/calc/{number1}/{number2}")
@ResponseBody
 public Calculator calc(@PathVariable("number1") int number1, 
        @PathVariable("number2") int number2){
    Calculator c = new Calculator(number1 , number2) ;
 return c;
}
}

Upvotes: 1

Related Questions