AngularJS: Creating a simple API Promise Factory

Many Angular applications require external API calls to Create, Read, Update, Delete (CRUD) data. Creating a reusable API factory simplifies the API call process by introducing a global CRUD object that can be used across all of your controllers. Promises are a core feature of AngularJS and uses the $http service to perform HTTP GETs, POSTs, PUTs and DELETEs on a API / URL.

api-factory

First, we will create the API Promise Factory, api.promise.factory.js

'use strict';
myApp.factory('apiPromise', ['$window', '$http', '$q', '$log', apiPromise]);

function apiPromise($window, $http, $q, $log) {

    var apiUrl = 'http://somethingapi.api.com';

    /**
     *
     * @param urlPath
     * @returns {*}
     */
    var get = function(urlPath,data) {
        var url = apiUrl + urlPath;

        $log.debug("Sending GET request to [" + urlPath + "]");
        return $http.get(url);
    };

    /**
     *
     * @param urlPath
     * @param data
     * @returns {*}
     */
    var post = function(urlPath, data) {
        var url = apiUrl + urlPath;

        $log.debug("Sending POST request to [" + urlPath + "] and sent DATA [" + data + "]");
        return $http.post(url, data);
    };


    /**
     *
     * @param urlPath
     * @param data
     * @returns {*}
     */
    var put = function(urlPath, data) {
        var url = apiUrl + urlPath;

        $log.debug("Sending PUT request to [" + urlPath + "] and sent DATA [" + data + "]");
        return $http.put(url, data);
    };

    /**
     *
     * @param urlPath
     * @returns {*}
     */
    var remove = function(urlPath, data) {
        var url = apiUrl + urlPath;

        $log.debug("Sending DELETE request to [" + urlPath + "]");
        return $http.delete(url);
    };
	
return {
        /**
         *
         * @param data
         * @returns {*}
         */
        getSomething: function(data) {
            var apiPath = '/something/';
            return get(apiPath, data);
        },
        /**
         *
         * @param data
         * @returns {*}
         */
        createSomething: function(data) {
            var apiPath = '/something/create/';
            return post(apiPath, data);
        },
        /**
         *
         * @param data
         * @returns {*}
         */
        updateSomething: function(data) {
            var apiPath = '/something/update/';
            return put(apiPath, data);
        },
        /**
         *
         * @param data
         * @returns {*}
         */
        deleteSomething: function(data) {
            var apiPath = '/something/delete';
            return remove(apiPath, data);
        }

    };



}

Next, we will create a controller to handle the specific click events / requests on the UI (Create, Update, Delete), something.controller.js

function somethingCtrl($scope, $rootScope, $log, apiPromise,somethingFactory, sessionFactory) {

  $scope.sendGet = function (data) {
    somethingFactory.getSomething(data)
      .then(
        function (data) { //Success Function
          $log.debug("SUCCESS - " + JSON.stringify(data));
        },
        function (error) { //Error Function
          $log.debug("FAIL - " + JSON.stringify(error));
        });
    };
  $scope.sendCreate = function (data) {
    somethingFactory.createSomething(data)
      .then(
        function (data) { //Success Function
          $log.debug("SUCCESS - " + JSON.stringify(data));
        },
        function (error) { //Error Function
          $log.debug("FAIL - " + JSON.stringify(error));
        });
    };

  $scope.sendUpdate = function (data) {
    somethingFactory.updateSomething(data)
      .then(
        function (data) { //Success Function
          $log.debug("SUCCESS - " + JSON.stringify(data));
        },
        function (error) { //Error Function
          $log.debug("FAIL - " + JSON.stringify(error));
        });
    };
  $scope.sendDelete = function (data) {
    somethingFactory.deleteSomething(data)
      .then(
        function (data) { //Success Function
          $log.debug("SUCCESS - " + JSON.stringify(data));
        },
        function (error) { //Error Function
          $log.debug("FAIL - " + JSON.stringify(error));
        });
    };
}

Next, we will create the factory that will initialize the API requests, something.factory.js

'use strict';
/**
 * @name somethingFactory
 * @description
 *
 * Factory that maintains the current session information of the user
 */
myApp.factory('somethingFactory', ['$log','$q','apiPromise', somethingFactory, data]);

function somethingFactory($log,$q,apiPromise, data) {
    $log.debug("somethingFactory Initialized");

    /**
     * Contains all code that is executed when this factory is initialized
     */
    function init(){
          $scope.Data = apiPromise.getSomething(data);
    };


    //Call the init function to initialize things
    init(data);

    /**
     * Export the variables/functions for this factory
     */
    return {
        getSomething : function(data) {
            return apiPromise.getSomething(data);
        },
        createSomething : function(data) {
            return apiPromise.createSomething(data);
        },
        updateSomething : function (data) {
            return apiPromise.updateThemePublishStatus(data);
        },        
        deleteSomething : function(data) {
            return apiPromise.deleteSomething(data);
        },

    }

};

Lastly, we will want to create the view and call specific API calls:

In your index.html (wrapper) add in the following controllers / factory includes in <head></head>:

<script type="public/services/something.controller.js"></script>
<script type="public/services/something.factory.js"></script>

<script type="public/services/api.promise.factory.js"></script>

Create a partial / template to handle your data, something.html:

<h1><span style="color: #cc0000;">Something</span> Hello, world!</h1>
<p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p>

 <table class="table table-condensed" ng-controller="somethingController">
	<div style="padding: 15px 0;">
		<input type="text" style="width: 820px; padding-left: 20px;" /> <input type="button" ng-click="createSomething(data)" class="button btn-primary" value="Create Something" />
	</div>
    <thead>
      <tr>
		<th>ID</th>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="data as data">
		<td>{{data.id}}</td>
        <td>{{data.firstname}}</td>
        <td>{{data.lastname}}</td>
        <td>{{data.email}}/td>
		<td><a href="#" ng-click="sendEdit(data.id);" class="btn btn-success btn-small">Edit</a> <a href="#" ng-click="sendDelete(data.id);" class="btn btn-danger btn-small">Delete</a></td>
      </tr>
    </tbody>
  </table>

api-factory

Categories AngularJS, API Factory

Leave a Reply