Common POST Function for Angular through Services

140 views Asked by At

We are building an angular app which is having multiple functions based on GET, POST and PUT methods. For Example

this.updateEmp = function (employee) {
    var response = $http({
        method: "post",
        url: "Home/UpdateEmployee",
        data: JSON.stringify(employee),
        dataType: "json"
    });
    return response;
}

    this.AddEmp = function (employee) {
    var response = $http({
        method: "post",
        url: "Home/AddEmployee",
        data: JSON.stringify(employee),
        dataType: "json"
    });
    return response;
}

My question is, is there any way to make this function common in common controller and only URL passing is enough in service.?

1

There are 1 answers

1
jitender On BEST ANSWER

You may create a simple service as follow and use on desired location

 angular.module('myApp')
.service('ajaxService', function($http) {
   this.post = function(url,data){
    $http({
    method: "post",
    url: url,
    data: JSON.stringify(data),
    dataType: "json"
   });
 }      
}

for example

this.updateEmp = function (employee) {
return ajaxService.post("Home/UpdateEmployee",employee)  
}