首页 > 代码库 > AngularJS ——ngResource、RESTful APIs 使用

AngularJS ——ngResource、RESTful APIs 使用

这篇文章里,用以下两个情景用例来解释:

保存/持久化 新的数据对象

更新存在的数据对象

代码片段包含了AngularJs代码和Spring MVC代码,以能够让你简单快速的上手。

想要$resource 服务工作,需要添加一段实际代码:

应用angular-resource.js文件,你可以使用Google Hosted Libraries来实现。

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-resource.js">
</script>
下面的代码告诉你如何在创建控制器时引入ngResource模块和注入$resource服务:

var helloApp = angular.module("helloApp", [ ‘ngResource‘ ]);
helloApp.controller("HttpController", [ ‘$scope‘, ‘$resource‘, function($scope, $resource) {
//
// 在这写你的实际业务代码...
//
} ]);

 

保存/持久化新对象 (其实就是传给后台存进数据库的一个过程)

下面的代码演示了如何使用POST方法提交form表单中的user信息(这部分是由controller来做),controller会把uers信息提交给REST URL “/user/new”(这部分是Spring MVC的控制器执行)。


AngularJS代码

var helloApp = angular.module("helloApp", [ ‘ngResource‘ ]);helloApp.controller("HttpController", [ ‘$scope‘, ‘$resource‘,     function($scope, $resource) {    $scope.users = [        { ‘firstname‘:‘Ajitesh‘,        ‘lastname‘:‘Shukla‘,        ‘address‘:‘Hyderbad‘,        ‘email‘:‘ajitesh101@gmail.com‘},        { ‘firstname‘:‘Sumit‘,            ‘lastname‘:‘Jha‘,            ‘address‘:‘Muzaffarpur‘,            ‘email‘:‘sumitjha2011@yahoo.com‘},                                                                                ];     $scope.saveUser = function(){                                    // 创建一个resource对象        //        var User = $resource(‘/user/new‘);        // 调用save方法        //(其实和我们$http.post(url,data).success(function(){})是一样一样的,只是它封装一下而已)        User.save({firstname:$scope.firstname,lastname:$scope.lastname,address:$scope.address,email:$scope.email}, function(response){            $scope.message = response.message;      

  

Spring MVC 代码

请注意User对象的字段要和JSON数据的要一致。同时确保Jackson包已经引入了,并且正常工作了。这是最重要的步骤。我推荐参考这篇文章 how to fix 415 Unsupported Mediatype error 来帮助你实现前面两个步骤。(1.Spring转对象的时候,是按照字段名来转的,比如你的Java的User对象的firstname会绑定Json对象的firstname,所以需要保持一致,否则帮出来的数据可能不对。2.不引人Jackson包,那么Json对象和Java对象不能想换转化,也就不能正常工作了)

/ 创建一个新user

//@RequestMapping(value = "http://www.mamicode.com/user/new", method = RequestMethod.POST) public @ResponseBody String saveUserRestful( @RequestBody User user ) { //// 处理输入参数的代码// String response = "{\"message\":\"Post With ngResource: The user firstname: " + user.getFirstname() + ", lastname: " + user.getLastname() + ", address: " + user.getAddress() + ", email: " + user.getEmail()+"\"}";return response;}

  

更新已存在的数据对象

下面的代码演示了如何通过POST方法提交表单信息来更新user对象,请求会发送到服务器的REST URL "/user/{id}",也包括Spring MVC的方法。


AngularJS代码

var helloApp = angular.module("helloApp", [ ‘ngResource‘ ]);helloApp.controller("HttpController", [ ‘$scope‘, ‘$resource‘, function($scope, $resource) {    $scope.users = [        { ‘firstname‘:‘Ajitesh‘,        ‘lastname‘:‘Shukla‘,        ‘address‘:‘Hyderbad‘,        ‘email‘:‘ajitesh101@gmail.com‘},        { ‘firstname‘:‘Sumit‘,            ‘lastname‘:‘Jha‘,            ‘address‘:‘Muzaffarpur‘,            ‘email‘:‘sumitjha2011@yahoo.com‘},                                                                                ];     $scope.updateUser = function(){                                    // Create a resource class object        //        var User = $resource(‘/user/:userId‘, {userId:‘@id‘});        // Create an instance of User resource        var user = User.get({userId:25});        // Update the new values entered in the form fields        //        user.id = 25;        user.firstname = $scope.firstname;        user.lastname = $scope.lastname;        user.address = $scope.address;        user.email = $scope.email;        // Call ‘$‘ prefixed action menthod to post ("save" )        //        user.$save(function(response){            $scope.message = response.message;        });        // Push the new objects in the $scope.users                             //        $scope.users.push({ ‘firstname‘:$scope.firstname, ‘lastname‘: $scope.lastname, ‘address‘:$scope.address, ‘email‘:$scope.email });        $scope.firstname=‘‘;        $scope.lastname=‘‘;        $scope.address=‘‘;        $scope.email=‘‘;    }         } ]);

  


Spring MVC 代码

请注意下面几点

-用例的路径变量(就是"/user/{id}"这东西)

-Java的User对象要和Json对象匹配(字段名,或者说是属性名)

-确保Jackson包引入并且正常工作(确保你后台能正常转化Json和java对象)

// 更新 user//    @RequestMapping(value = "http://www.mamicode.com/user/{id}", method = RequestMethod.POST)    public  @ResponseBody String updateUserProfile( @PathVariable("id") long userId,  @RequestBody User user  )   {            //    // Code processing the input parameters    //        String response = "{\"message\":\"Post With ngResource - id: " + String.valueOf( userId ) + ",firstname: " + user.getFirstname() + ", lastname: " + user.getLastname() + ", address: " + user.getAddress() + ", email: " + user.getEmail() +"\"}";    return response;}

  

 

 

 

AngularJS ——ngResource、RESTful APIs 使用