There are two REST calls:
The first one is:
http://localhost:8080/sample/rest/ser/out/2
Which returns:
{"num":"2"}
The second REST call is:
http://localhost:8080/sample/rest/ser/person/list2/two
Which returns:
[{"personName":"Rahul Shivsharan","personId":123},{"personName":"Mehul Sarnikar","personId":34},{"personName":"Praful Patel","personId":343}]
In order to invoke the second REST call based on the response of the first one, I have implemented an AngularJS code as follows:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javaScript" src="../scripts/angular.js"></script>
<script src="../scripts/angular-resource.js"></script>
<script type="text/javascript">
var myApp = angular.module("myApp",['ngResource']);
myApp.factory("CountService",function($resource){
return $resource("../rest/ser/out/:num",{
num : "@num"
});
}).factory("PersonService",function($resource,CountService,$interval){
var obj = new Object();
obj.getPersonList = function(inputTxt){
return CountService.get({
"num" : inputTxt
}).$promise.then(function(response){
var url = "../rest/ser/person/list2/";
if(response.num === 2){
url += "two";
}else if(response.num === 3){
url += "three";
}else{
url += "other";
}
return $resource(url,{});
});
};
return obj;
}).controller("myCtrl",function($scope,PersonService){
$scope.getInfo = function(){
PersonService.getPersonList($scope.inputTxt).query().$promise.then(function(response){
$scope.personList = response;
});
}
});
</script>
</head>
<body ng-controller="myCtrl">
<h1>{{num}}</h1>
<br />
<input type="text" ng-model="inputTxt" /><br/><br/>
<input type="button" value="ENTER" ng-click="getInfo()" />
<br /><br /><br />
<table border="2">
<tr ng-repeat="per in personList">
<td>{{per.personName}}</td>
<td>{{per.personId}}</td>
</tr>
</table>
</body>
The functionality of this code is based on user input for the first REST call, followed by the execution of the second REST call after the success of the first. The response from the first call is converted to match the URL parameters of the second call.
However, there seems to be an error:
Error Message:
TypeError: PersonService.getPersonList(...).query is not a function
at Scope.$scope.getInfo (index.html:65)
at Parser.functionCall (angular.js:10795)
at angular.js:19036
at Scope.$get.Scope.$eval (angular.js:12632)
at Scope.$get.Scope.$apply (angular.js:12730)
at HTMLInputElement.<anonymous> (angular.js:19035)
at angular.js:2843
at forEach (angular.js:325)
at HTMLInputElement.eventHandler (angular.js:2842)
I thought that a promise should return another promise which should work properly, but it doesn't. Can you suggest a better solution and point out where I might have gone wrong?