使用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);
      };
    });
}]);
dsfsdfsdfsdf6455
dsfsdfsdfsdf6455 其次,您要在整个地方向$scope服务添加方法。由于这些基本上是您的控制器的“API”,我强烈建议它们都在文件顶部的单行赋值语句中定义,以便一目了然,您的控制器实际上做了什么。
大约 3 年之前 回复
dongquan0024
dongquan0024 首先,正如其他人所说,你应该避免依赖控制器中的$http服务。将这些依赖项封装到数据检索服务中,并在控制器中使用这些方法。
大约 3 年之前 回复
dqx13503925528
dqx13503925528 在图片之外,我认为如果您从工厂/服务发送请求会好得多。我可以提供给你的另一个提示就是使用$http.post(),除了$http({method:'POST'})
大约 3 年之前 回复

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;

        }
    }
})();
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐