【发布时间】:2016-01-07 20:03:59
【问题描述】:
AngularJS 应用程序需要从 Spring Boot 后端调用的 REST 服务中检索 JSON 对象。如何修改下面的代码,以便将响应解析为返回的 JSON 对象的属性?
例如,我想在 JSON 对象返回后提取 firstname、lastname 和其他属性。
这里是调用 REST 服务的 AngularJS 控制器:
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);
});
});
这里是传递 JSON 响应的 Spring Boot 方法:
@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;}
}
注意:我们知道帖子是在服务器上处理的,因为/confirm-email处理程序中以SYSO开头的终端日志是:
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
【问题讨论】:
-
网络服务返回的 JSON 是什么?
-
@Dan 我不确定,因为
console.log(response)没有返回任何内容。程序在该行的断点之前冻结,但终端日志显示调用了服务器端方法。 -
(专业提示:元注释在这里的问题中通常不太合适。没有接受答案的问题默认被视为未得到满意回答。如果您想澄清一个问题,然后尽一切办法 (a) 在您的帖子的末尾添加一个澄清,解释可能出现的误解,(b) 尽量不要暗示读者已经猜到或垃圾邮件 - 大多数人只是试图提供帮助,(c) 避免投票评论 - 大多数读者不感兴趣,甚至不登录)。
标签: javascript angularjs json ajax spring