0

У меня есть контроллер, который вызывает методы http.get, http.push и http.post.Как преобразовать http-вызов контроллера в шаблон Service/factory, который принимает параметр

Я изучаю angularjs и обнаружил, что лучше всего называть ваш http.get в вашем служебном файле. Я могу сделать это с помощью простого http.get, но запутаться с http.get по идентификатору или http.get/http.post который принимает параметр:

Мой текущий контроллер выглядит следующим образом

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

Я хочу, чтобы отделить ее, как этого

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") 
    }; 

}; 

ответ

2

Простой. Сделайте фабрику, которая принимает параметры.

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

Используйте службу в контроллере:

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 
     }); 
    } 

}]); 
Смежные вопросы