0

einnimmt Ich habe einen Controller, der http.get, http.push und http.post-Methoden aufruft.Wie konvertiere ich einen Controller-HTTP-Aufruf in ein Service/Factory-Muster, das einen Parameter

Ich lerne angularjs und habe festgestellt, dass es am besten ist, Ihr http.get in Ihrer Servicedatei aufzurufen. Ich bin in der Lage, dass mit einem einfachen http.get zu tun, aber verwirrt mit einem http.get von id oder http.get/http.post, die einen Parameter nimmt:

Mein aktueller Controller wie diese

angular.module("app-complaints") 
.controller("clcontrol", clcontrol); 

function clcontrol($routeParams, $http, $scope) { 
$http.get(baseURL + "/api/complaints/" + $scope.complaintCase + "/checklists") 
    .then(function (cl) { 
     //success 
     $scope.index = 0; 
     $scope.cl = []; 
     $scope.cl = cl; 
} 
sieht

ich möchte es trennen ähnliche

controller.js

angular.module("app-complaints") 
.controller('clcontrol', function ($http, $scope, $q, Service, $timeout) { 
.... 
getCL(); 
function getCL(){ 
Service.getCl() 
.success(function(cl){ 
$scope.cl = []; 
$scope.cl = cl; 
} 

service.js

angular.module("app-complaints") 
.factory('Service', ['$http', function ($http) { 
     Service.getCL = function() { 
     return $http.get(urlBase + "/api/complaints/" + complaintCase + "/checklists") 
    }; 

}; 

Antwort

2

Einfach. Stellen Sie eine Fabrik her, die Parameter akzeptiert.

var app = angular.module("MyApp", [ /* dependencies */]); 

app.factory("SharedServices", ["$http", function($http) { 
    return { 
     getItems: function(url, parameters) { 
      return $http.get(url, { 
       //optional query string like {userId: user.id} -> ?userId=value 
       params: parameters 
      }); 
     }, 
     postItem: function(url, item) { 
      var payload = { 
       item: item 
      }; 
      return $http.post(url, payload); 
     }, 
     deleteItem: function(url, item) { 
      var payload = { 
       item: item 
      }; 
      return $http({ 
       url: url, 
       data: payload, 
       method: 'DELETE', 
      }); 
     } 
     // ETC. ETC. ETC. 
     // follow this pattern for methods like PUT, POST, anything you need 
    }; 
}]); 

Nutzen Sie den Service in Ihrem Controller:

app.controller("MainCtrl", ["$scope","SharedServices", function($scope, SharedServices) { 

    //do things with the shared service 
    $scope.postMyThings = function() { 
     SharedServices.postItems('path/to/api', itemsArray).then(function(response) { 
      //success callback, do something with response.data 
     }, function(response) { 
      //an error has occurred 
     }); 
    }; 

    $scope.getMyThing = function() { 
     SharedServices.getItems('path/to/api/get').then(function(response) { 
      //success callback, do something with response.data 
     }, function(response) { 
      //an error has occurred 
     }); 
    } 

}]);