2017-09-27 137 views
1

所以,我做了一個待辦事項列表使用angularjs,並作出api使用php slim frameworkmysql任務存儲。 我試圖使用$http服務來保存/刪除/更新數據庫中的任務,到目前爲止,我想出了這個(代碼如下),但由於我不是這方面的專家,所以可能有很多關鍵錯誤。

請記住,有關待辦事項列表的代碼正常工作,我希望爲$http請求提供一些指導和提示。

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); 
     }; 
    }); 
}]); 
+0

畫外,我認爲如果您從工廠/服務發送請求會更好。這個請求我可以提供給你的另一個提示是使用'$ http.post()',除了'$ http({method:'POST'})' –

+0

首先,正如其他人所說的,你應該避免依賴控制器中的$ http服務。將這些依賴關係封裝到數據檢索服務中,並在您的控制器中使用這些方法。 – 10BitDev

+0

其次,您將方法添加到$ scope服務到處。由於這些實質上就是您的控制器的「API」,我強烈建議將它們全部定義在文件頂部的單行賦值語句中,以便一目瞭然地瞭解您的控制器實際執行的操作。 – 10BitDev

回答

0

請找到下面的模塊來實現數據與寧靜的API相關的溝通。它也使用驗證頭和$ q服務來實現將服務結果集傳遞給控制器​​的承諾:

(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; 

     } 
    } 
})();