-1

I have controller which fetches some data and adds some extra items based on the information. The information should be searchable. I have working code for that now, but was wondering what is the best way to reuse the code? Is it directives? factory? Here is the code :

app.controller('searchProducts', function($scope, $http) { $scope.search = function(val) { $scope.val = val; //from here let query; if(!$scope.val) { query = BASE_URL+"Products"; } if($scope.val) { query = encodeURI("Products?$filter=contains(ProductName,\'"+val+"\')"); query = BASE_URL+query; } $http.get(query) .then(function(response) { $scope.rawData = response.data; angular.forEach($scope.rawData.value, function(value) { //looping the data, replacing the IDs with actual data from the source //Getting actual Supplier using SupplierID $http.get("http://services.odata.org/V4/Northwind/Northwind.svc/Suppliers("+value.SupplierID+")/CompanyName/$value") .then(function(response) { value.Supplier = response.data; }) //Getting actual Category using CategoryID $http.get("http://services.odata.org/V4/Northwind/Northwind.svc/Categories("+value.CategoryID+")/CategoryName/$value") .then(function(response) { value.Category = response.data; }) }); }) //to here } //is repeated here }); 
3
  • 2
    make a service or factoriy for your http calls. Commented May 8, 2018 at 20:46
  • I tried creating a service, but are having some problems with including it in my controller. The code for that is here: pastebin.com/xc9MW081 Commented May 8, 2018 at 21:13
  • It will work better if you return the $http promise. Commented May 8, 2018 at 21:29

1 Answer 1

2

You would use a factory and bundle that behavior in one or more methods, i.e.

app.factory('myFactory', function($http, $q) { return { myRequest: function(query) { return $http.get(query).then(this.myHandler); }, myHandler: function(response) { var categoryPromises = []; var supplierPromises = []; angular.forEach(response.data, function(value) { supplierPromises.push($http.get("http://services.odata.org/V4/Northwind/Northwind.svc/Suppliers("+value.SupplierID+")/CompanyName/$value")); categoryPromises.push($http.get("http://services.odata.org/V4/Northwind/Northwind.svc/Categories("+value.CategoryID+")/CategoryName/$value")); }); return $q.all([$q.all(supplierPromises), $q.all(valuePromises)]); } }; }); // and to invoke the factory app.controller('myController', function(myFactory) { myFactory.myRequest('/path/to/resource') .then(function(results) { //... handle your results }) .catch(function(e) { throw e; }); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.