简体   繁体   中英

Angularjs $http request using rest api

So, I made a todo list using angularjs and made an api using php slim framework and mysql for task storage. I'm trying to use the $http service to save/delete/update tasks in the DB and so far, I came up with this (code below) but since I'm no expert in this matter, there's probably a lot of crucial mistakes.

Keep in mind that, the code regarding the todo list works fine and I'd like some guidance and tips for the $http requests.

JS:

var app = angular.module('todoApp', []);
app.controller('TodoListController', ['$scope', '$http', function ($scope, $http) {
  $scope.todos = [];
  $scope.newField = [];
  $scope.customStyle = {};
  $scope.date = new Date();

  $http({
    method: 'POST',
    url: 'http://taskapi.dev/api/tasks/add' }).then(function successCallback (response) {
      $scope.addTodo = function () {
        $scope.todos.push({text: $scope.todoText, done: false, editing: false, date: new Date()});
        $scope.todoText = '';
      };

      $scope.save = function (index) {
        $scope.todos[index].editing = false;
        $scope.todos[index].createdOn = new Date().getTime();
      };
    });

  $http({
    method: 'PUT',
    url: 'http://taskapi.dev/api/tasks/update' }).then(function successCallback (response) {
      $scope.editTodo = function (todo) {
        todo.editing = true;
      };

      $scope.change = function (field) {
        var todoIndex = $scope.todos.indexOf(field);
        $scope.newField[todoIndex] = angular.copy(field);
        $scope.todos[todoIndex].editing = true;
        $scope.todos[todoIndex].LastModifyOn = new Date().getTime();
      };

      $scope.turnGreen = function (todo) {
        todo.customStyle = {'background': 'green'};
      };

      $scope.turnYellow = function (todo) {
        todo.customStyle = {'background': 'yellow'};
      };

      $scope.turnRed = function (todo) {
        todo.customStyle = {'background': 'red'};
      };

      $scope.cancel = function (index) {
        $scope.todos[index] = $scope.newField[index];
      };
    });

  $http({
    method: 'DELETE',
    url: 'http://taskapi.dev/api/tasks/delete' }).then(function successCallback (response) {
      $scope.delete = function () {
        var oldTodos = $scope.todos;
        $scope.todos = [];
        angular.forEach(oldTodos, function (todo) {
          if (!todo.done) $scope.todos.push(todo);
        });
      };

      $scope.remove = function () {
        $scope.todos.splice(this.$index, 1);
      };
    });
}]);

Please find following module to implement data related communication with restful api. it also uses authentication header and $q service to implement promises to pass result set from service to controller:

(function () {
    'use strict';

    angular
        .module('core')
        .factory('datacontext', datacontext);

    datacontext.$inject = ['$http', '$q', 'config', 'exceptionHandler', '$rootScope', 'cookies'];

    function datacontext($http, $q, config, exceptionHandler, $rootScope, cookies) {
        var service = {
            get: get,
            getById: getById,
            post: post,
            put: put,
            patch: patch,
            deleteById: deleteById,
            deleteObject: deleteObject,
            getImage:getImage
        };
        var baseUrl = config.baseApiUrl;
        return service;

        function get(partialUrl) {
            var reqConfig = {
                headers: {
                    'Authorization': 'bearer ' + cookies.get("user_authToken")
                }
            };
            var reqUrl = config.baseApiUrl + partialUrl;
            var deffered = $q.defer();
            $http.get(reqUrl, reqConfig).success(deffered.resolve).catch(function (data) {
                handleCatch(data);
            });

            //$http.get(reqUrl).success(handdleSuccess(deffered)).catch(function (data) {
            //    handleCatch(data);
            //});
            return deffered.promise;
        }
        //function getUnAuth(partialUrl) {

        //    var reqUrl = config.baseApiUrl + partialUrl;
        //    var deffered = $q.defer();
        //    $http.get(reqUrl).success(deffered.resolve).catch(function (data) {
        //        handleCatch(data);
        //    });
        //    return deffered.promise;
        //}

        function getById(resource, id) {
            var reqConfig = {
                headers: {
                    'Authorization': 'bearer ' + cookies.get("user_authToken")
                }
            };
            var deffered = $q.defer();
            var url = baseUrl + resource + "/" + id;
            $http.get(url, reqConfig).success(deffered.resolve).catch(function (data) {
                handleCatch(data);
            });
            return deffered.promise;
        }
        function post(resource, obj) {
            var reqConfig = {
                headers: {
                    'Authorization': 'bearer ' + cookies.get("user_authToken")
                }
            };
            var deffered = $q.defer();
            var url = baseUrl + resource;
            $http.post(url, obj, reqConfig).success(deffered.resolve).error(deffered.reject).catch(function (data) {
                handleCatch(data);
            });
            return deffered.promise;
        }
        function put(resource, obj) {
            var reqConfig = {
                headers: {
                    'Authorization': 'bearer ' + cookies.get("user_authToken")
                }
            };
            var deffered = $q.defer();
            var url = baseUrl + resource;
            $http.put(url, obj, reqConfig).success(deffered.resolve).catch(function (data) {
                handleCatch(data);
            });
            return deffered.promise;
        }
        function patch(resource, obj) {
            var reqConfig = {
                headers: {
                    'Authorization': 'bearer ' + cookies.get("user_authToken")
                }
            };
            var deffered = $q.defer();
            var url = baseUrl + resource;
            $http.patch(url, obj, reqConfig).success(deffered.resolve).catch(function (data) {
                handleCatch(data);
            });
            return deffered.promise;
        }
        function deleteById(resource, id) {
            var reqConfig = {
                headers: {
                    'Authorization': 'bearer ' + cookies.get("user_authToken")
                }
            };
            var deffered = $q.defer();
            var url = baseUrl + resource + "/" + id;
            $http.delete(url, reqConfig).success(deffered.resolve).catch(function (data) {
                handleCatch(data);
            });
            return deffered.promise;
        }
        function deleteObject(resource, obj) {
            var reqConfig = {
                headers: {
                    'Authorization': 'bearer ' + cookies.get("user_authToken")
                }
            };
            var deffered = $q.defer();
            var url = baseUrl + resource;
            $http.delete(url, obj, reqConfig).success(deffered.resolve).catch(function (data) {
                handleCatch(data);
            });
            return deffered.promise;
        }
        //local function to build error msg
        function handleCatch(data) {
            $rootScope.processing = false;
            //stop spinner if exception occurs
            //common.toggleSpinnerActivity(false);
            exceptionHandler.catchException(config.webApiError)(data);
            var reqConfig = {
                headers: {
                    'Authorization': 'bearer ' + cookies.get("user_authToken")
                }
            };
             var errorLogObj = {
                ErrorMessage: data.data.Message,
                ErrorType: 'Javascript Error',
                ErrorSource: data.config.url,
                ErrorPriority: 3,
                ErrorCode: data.status,
                ReasonPhrase: data.statusText
            }
            var url = baseUrl + "/log"
            $http.post(url, errorLogObj, reqConfig)
            .success(function (data) {
            })
            .error(function (data) {
            });
        }
        function handdleSuccess(deffered) {
            deffered.resolve();
        }
        function getImage(partialUrl) {
            var deffered = $q.defer();
            var reqUrl = config.baseApiUrl + partialUrl;

            $http({
                method: 'GET',
                url: reqUrl,
                responseType: 'arraybuffer',
                headers: {
                    'Authorization': 'bearer ' + cookies.get("user_authToken")
                }
            })
                .success(function (results) {
                    if (results !== undefined) {
                        var file = new Blob([results], {
                            type: 'application/octet-stream'
                        });
                        var fileURL = URL.createObjectURL(file);
                        deffered.resolve(fileURL);
                    } else {
                        deffered.reject(new Error("No motive!"));
                    }
                })
                .error(function (results) {
                    deffered.reject(new Error(results));
                });
            return deffered.promise;

        }
    }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM