Submit Request in AngularJs Single Page Application

I am creating a single page application in Spring MVC and AngularJS. I have a header / footer bar and an ng-view section where all pages are loaded by Ajax using routeProvider. The fact is that routeProvider only works with GET requests , which means that I cannot pass any parameters. ( I don’t want to pass all the form data to the URL ) I want to submit the form using an AJAX POST request and at the same time change the contents of ng-view. Is this possible with Angular routeProvider?

The solution I was thinking so far is to submit the form data, receive a successful message, and then change the hash of the URL to trigger a new server request for a new page. However, this solution has the disadvantage of making 2 requests to the server, while I want to execute only one.

thank

+4
source share
1 answer

First of all, you need to understand that routeProviders is there to change routes, insider applications, and not transfer data to the server. use a service or factory to transfer data to the server and open the response page. here is a simple example

The form

: -

<form name="empForm" ng-controller="insertEmpCtrl" ng-submit="insertEmp()">
name: <input type="text" class="form-control" name="lname" ng-model="formData.lname"/>
<input type="submit" value="Save" />

Routing: -

myApp.config(function($routeProvider){
$routeProvider
    .when('/',{
        templateUrl : '/your/project/root.html',
        controller : 'controler1'
    })
    .when('/page',{
        templateUrl : '/your/project/page.html',
        controller : 'controler2'
    });
});

factory: -

myApp.factory('factoryname', function(){
return{
    insertData: function($scope,$http){
        var json_data = JSON.stringify($scope.formData);


        $http.post(url, json_data, {
            withCredentials: true,
            headers: {'Content-Type': 'application/json'},
            transformRequest: angular.identity
        }).success(function(){
            console.log("done");
        }).error(function(){
            console.log("error");
        });
    }
}
});

controller: -

myApp.controller('controller1',['$scope','$http','$rootScope','factoryname',function($scope,$http,$rootScope,factoryname){

$scope.insertEmp = function(){

    $scope.formFactory = factoryname.insertData($scope,$http);

};
}]);

spring controller: -

@RequestMapping(value="/aurlPattern",method = RequestMethod.POST)
public String insertmethod(@RequestBody  FormModelObject FormModelObject) {

    //do something


    return "responsePage";
}
+2
source

Source: https://habr.com/ru/post/1538963/


All Articles