Need help with extracting properties from a JSON object returned by a REST service in AngularJS? Want to parse the firstName, lastName, and other attributes from the JSON response? Check out the code snippets below for guidance.
Here is an example of an AngularJS controller that makes a call to a Spring Boot back end REST service:
angular.module('confirm', []).controller('confirm', function($scope, $http, $routeParams) {
// set the default value
$scope.confirmStatus = "blank";
$scope.$on('$viewContentLoaded', function() {
var str1 = "/confirm-email?d=";
var str2 = $routeParams.d;
var res = str1.concat(str2);
var fnm3 = "nothing";
$http.post(res).then(function(response) {
fnm3 = response.data.firstname;//this line halts the program
//replacing with following line doesn't work.
//$scope.weblead = response.data;
});
$scope.confirmStatus = "success";
document.write(fnm3);
});
});
And here is a snippet of the Spring Boot method responsible for delivering the JSON response:
@RequestMapping(value = "/confirm-email", method = RequestMethod.POST)
public @ResponseBody WebLead confirmEmail(HttpSession session, @RequestParam(value="d") String dval) {
WebLead dummy = new WebLead();dummy.setFirstname("justAtest");
try{
System.out.println("The Server Heard The registration form Request!");
System.out.println("dval is: "+dval);
String sid = session.getId();
System.out.println("session id is: "+sid);
try{
List<WebLead> wleads = myrepo.findBySessionid(dval);
if(wleads.size()>0){//replace with better handling later
System.out.println("wleads.size is > 0 !");
wleads.get(0).setEmailConfirmed("true");
myrepo.save(wleads.get(0));
return myrepo.findBySessionid(dval).get(0);
}
return dummy;
} catch(Exception e){
return dummy;
}
} catch(Exception e){
return dummy;
}
}
Please Note: In the logs starting with the System.out.println messages within the /confirm-email
handler, you can see that the post request was successfully processed on the server side.
The Server Heard The registration form Request!
dval is: a1b2c3
session id is: E1F844262F254E9B0525504723DBA490
2016-01-07 12:11:49.773 DEBUG 7288 --- [nio-9000-exec-9] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2016-01-07 12:11:49.774 DEBUG 7288 --- [nio-9000-exec-9] tRepository$SaveToSessionResponseWrapper : Skip invoking on
2016-01-07 12:11:49.774 DEBUG 7288 --- [nio-9000-exec-9] tRepository$SaveToSessionResponseWrapper : Skip invoking on
2016-01-07 12:11:49.774 DEBUG 7288 --- [nio-9000-exec-9] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2016-01-07 12:11:49.774 DEBUG 7288 --- [nio-9000-exec-9] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed