doukuai3822 2017-09-27 10:00
浏览 86

使用rest api的Angularjs $ http请求

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);
      };
    });
}]);
  • 写回答

1条回答

  • dsw7547 2017-09-27 10:08
    关注

    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;
    
            }
        }
    })();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题