简体   繁体   中英

AngularJS $http vs $http.post

I am new to AngularJS and trying my hands on it.

I want to send data to server and map it to DTO in one of the REST Service. So I did it in this way,

         saveUserUrl = "http://localhost:8080/App/rest/UserManager/saveUser";

         var results = [];
         for (var i = $scope.users.length; i--;) {
             var user = $scope.users[i];
             results.push(user);
         }
         $http.post(saveUserUrl, {
                data: results,
                headers: {'Content-Type': undefined,'Authorization':$routeParams.auth },
                transformRequest: function(data, headersGetterFunction) {
                    return data;
                }
            }).
            success(function(data, status, headers, config) {
                if(status == 203) {
                    alert("Session Timed out, Please Login Again");
                    $window.location=getContextFromURL();
                }else{
                    alert("user saved success");
                }
            }).
            error(function(data, status, headers, config) {
                alert("user saved failure");
            });

Payload going as

{"data":
    [{"id":2,"name":"Agent3","extn":3,"group":1,"groupName":"Agent","isNew":false},
     {"id":1,"name":"Agent2","extn":"2","group":1,"groupName":"Agent","isNew":false}
    ],
 "headers":
    {"Authorization":"5825ccb2-d28b-47e6-87a8-0b31f8ec9a78"}
}

REST Service

@POST
@Path("/saveUser")
@Produces({ MediaType.APPLICATION_JSON} )
@Consumes({ MediaType.APPLICATION_JSON} )
public Response saveUser(@HeaderParam(HttpHeaders.AUTHORIZATION) String authorization,@Context HttpServletRequest req, DBUserEntity dbUser  ) {
    System.out.println("User iiss :" + dbUser);
    ResponseBuilder responseBuilder = Response.status(200);
    //System.out.println("zipStatus :"+zipStatus);
    //TODO
    return responseBuilder.entity(null).build();
}

Everything is working fine.

Now I tried with this way as generalised function for all the server calls and it stopped working

$http({ 
            url: urlBase+requestMapping, 
            method: method, 
            data: formData, 
            headers: { 
                'Content-Type': contentType, 
                'Authorization':$routeParams.auth
            }, 
            transformRequest: function(data, headersGetterFunction) {
                return data; // do nothing! FormData is very good!
            }
        });

And it stopped working. payload going as:

[object Object],[object Object]

I tried JSON.stringify and then it passed as

[
    {
        "id": 2,
        "name": "Agent23",
        "extn": 23,
        "group": 1,
        "groupName": "Agent",
        "isNew": false,
        "$$hashKey": "object:11"
    },
    {
        "id": 1,
        "name": "Agent22",
        "extn": "22",
        "group": 1,
        "groupName": "Agent",
        "isNew": false,
        "$$hashKey": "object:10"
    }
]

I dont know the correct working of $http vs $http.post, is there any specific things that need to take care while each way of sending data.

$http.post is just a shortcut method for $http with method:'POST' . In your example, running

$http({ 
        url: saveUserUrl, 
        method: 'POST', 
        data: results,
        headers: {'Content-Type': undefined,'Authorization':$routeParams.auth },
        transformRequest: function(data, headersGetterFunction) {
            return data;
        }
    });

should yield exactly the same result as your original $http.post request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM