如何使用Restangular POST对象

How to POST object with Restangular?

本文关键字:对象 POST Restangular 何使用      更新时间:2023-09-26

我想用Angular JS和Restangular发送对象到Spring Controller。我就是这样做的:

var scoreTO = {
    score: parseFloat($scope.score.score),
    percentage: parseFloat($scope.score.percentage),
    date: (new Date()).getTime()
}
Restangular.one("scores").post(scoreTO);

有传输对象:

public class ScoreTO implements Serializable{
private double score;
private double percentage;
private long date;
public ScoreTO(){}
public ScoreTO(double score, double percentage, long date){
    this.score = score; this.percentage = percentage; this.date=date;
}
public double getScore() {
    return score;
}
public void setScore(double score) {
    this.score = score;
}
public double getPercentage() {
    return percentage;
}
public void setPercentage(double percentage) {
    this.percentage = percentage;
}
public long getDate() {
    return date;
}
public void setDate(long date) {
    this.date = date;
}
}

这就是我如何在Spring控制器中捕获请求:

@Controller
@RequestMapping(value="/score")
    public class ScoreController {
    (...)
    @RequestMapping(value="/scores", method= RequestMethod.POST)
    @ResponseBody
    public String saveScore(@RequestBody ScoreTO scoreTO){
        scoreService.saveScore(scoreTO.getScore(), scoreTO.getPercentage(), 
                new Date(scoreTO.getDate()));
        return "";
    }
}

但是如果我尝试发送它,我在浏览器控制台得到这个错误:POST http://localhost:8084/wpisywarkaAngular/score/scores/[object%20Object] 404 (Not Found)我做错了什么?如果有人能帮助我,我将非常高兴-提前谢谢你。

您必须使用all而不是one,另一种解决方案可以使用customPOST

Restangular.all("scores").post(scoreTO);