Common POST Function for Angular through Services

Issue

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.?

Solution

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)  
}

Answered By – jitender

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.