3

I got one controller CounterpartyCtrl that is used by two views.

The first view contains a selector which requires all the records from collection. So I fetch all the objects and put them into $scope.counterparties.

 app.controller('CounterpartyCtrl', [ '$scope', 'Counterparty', function($scope, Counterparty) {}, $scope.counterparties = {}, $scope.loadCounterparties = function() { Counterparty.query(function(response) {}); $scope.counterparties = response; }, $scope.loadCounterparties(); ]); 

The second view has to contain only counterparties divided by groups.

 $scope.customers $scope.vendors $scope.others $scope.HRs 

So, using the same controller I fetch them like the following

 app.controller('CounterpartyCtrl', [ '$scope', 'Counterparty', function($scope, Counterparty) {}, $scope.counterparties = {}, $scope.loadCounterparties = function() { Counterparty.query(function(response) {}); $scope.counterparties = response; $scope.customers = Counterparty.query({ group: 'Customer' }); $scope.vendors = Counterparty.query({ group: 'Vendor' }); $scope.others = Counterparty.query({ group: 'Other' }); $scope.HRs = Counterparty.query({ group: 'HR' }); }, $scope.loadCounterparties(); ]); 

As you can see here is obvious duplication of requests. On every view I make equal requests and therefore that is not productive. How can I refactor the code?

2
  • 1
    Use $q for counterparties.query, and return a promise. Then subsequent calls to counterparties.query doesn't do an HTTP request, but returns the value initially fetched. Commented Mar 7, 2016 at 22:09
  • @Jupo Could you provide an example in the answer? Commented Mar 7, 2016 at 22:13

2 Answers 2

1

here's what I meant about using $q and caching the result in the service to avoid multiple requests: http://plnkr.co/edit/3AeOjHaVo8MrY18tStEs

app.factory("dataService", ["$http","$q", function($http, $q){ var counterParties; return { query: function(param){ if(!counterParties){ counterParties = $q.defer(); $http.get("requestURL").then(function(response){ counterParties.resolve(response.data); }); } return counterParties.promise; } }; }]); 
Sign up to request clarification or add additional context in comments.

Comments

1

You could change your back end to return something like this

{ 'Customers': customers, 'Vendors': vendors, 'Other': others, 'HR': hrs } 

and then use that to make a full array, or just grab the parts you need based on when you call it. Only do this if all users would have access to all that data, and it's okay if they looked at the response data in the network tab. It will also put slightly more work on your front end for the client to process.

Hope this helps with what you were looking for.

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.