Monday, August 18, 2014

Creating service wrapper for restapi to database in AngularJs

I finally had some time this weekend to refactor my code and start writing services to access my database objects. What I really needed was some way to wrap around the $http service to make things more readable and logical in my code.

Here is my wrapper for access to the company data table.



var Company = angular.module('CompanyService',[]);
Company.factory('CompanySrv',
  ['$http',
   function ($http) {
   var CompanySrv = {
     data: {
      currentCompany: {},
      companies : []
     },
     getCompany: function (p_Id) {
      return $http.get(GloServername + "RestCompanies/getone/"+ p_Id + "/" + GetNewKey())
      .success(function success(data) {
       CompanySrv.data.currentCompany = data;
      })
      .error(function error() {
      });
     },
     getCompanies : function(p_Orderby,p_Zoekstring){
      var httprequest="";
      if (p_Zoekstring=="" || p_Zoekstring==null)
       httprequest = GloServername + "RestCompanies/" + p_Orderby + "/" + GetNewKey();
      else
       httprequest = GloServername + "RestCompanies/" + p_Orderby + "/" + p_Zoekstring + "/" + GetNewKey();
      return $http.get(httprequest)
      .success(function success(data) {
       CompanySrv.data.companies = data;
      })
      .error(function error() {
      });
     },
     insertCompany : function(company){
      return $http.post(GloServername + "RestCompanies/Post",company)
      .success(function(data, status, headers) {
      })
      .error(function(data, status, headers, config) {
      });
     },
     saveCompany : function(company){
      return $http.put(GloServername + "RestCompanies/Put",company)
      .success(function success() {
      })
      .error(function error() {
      });
     },
     deleteCompany : function(p_Id,p_Confirmation){
      if (p_Confirmation==true)
      {
       var retVal = confirm('Verwijder bedrijf');
       if (retVal!=true)
        return;
      }
      return $http.delete(GloServername + "RestCompanies/Delete/" + p_Id)
      .success(function success() {
       ;
      })
      .error(function error() {
       ;
      });
     }
   };
   return CompanySrv;
  }
  ]);  


Basically it contains crud code for insert,delete and updating company data, but it also contains a collection of companies, that can be filled with the getCompanies method. This method take two parameters, a filter and an order by string. Both will by passed by my Rest service, so the correct data is returned. This service is used in my controller. I generally create two controllers. One to manged my company grid, and one to manage my company form. The name of the controller says it all : CompaniesFormCtrl and CompaniesGridCtrl. Let me show you my CompaniesFormCtrl, this is the controller that's matching the From to edit my companies. The corresponding Html is named EditCompany.Html.

No comments: