0

I have a custom directive that is going to be on the same page in 2 different locations using 2 different data sets but all the data comes back with one service call. How can I make the API call once and use the data in both instances of the directive?

1
  • Please provide basic code outline. you are asking people to wire up 3 different components and haven't provided a single byte of code ... that's just not right Commented Jan 28, 2015 at 1:16

2 Answers 2

2

You can return a promise from the service after it's called the first time. So both of the directives might call service.getData().then(directiveCallback) but the service only fetches the data once from the server. In the service, something like:

var serverRequestPending = false;
var dataAlreadyRetrieved = false;
var dataPromise;

this.getData = function() {
   return getDataFromServer();
}

function getDataFromServer() {
    // don't do re-work
    if (dataAlreadyRetrieved || serverRequestPending) {
        return dataPromise;
    }


    serverRequestPending = true;

    dataPromise = apiCallHere(); // your custom API behavior that should return a promise and will resolve with the data
    dataPromise.then(onDataGetComplete);

    return dataPromise;
}

function onDataGetComplete() {
    dataAlreadyRetrieved = true;
    serverRequestPending = false;
}
Sign up to request clarification or add additional context in comments.

Comments

1

in any case this should always be handled by a service, which one to use and how to handle it, depends on your application, 2 ways using services are

1- (my favorite) use your service to get the data from the server and use $cacheFactory to cache the response and serve it to the rest of the directives

https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache. i like this one better because it abstracts your directive and service from the maintaining the data.

2- keep the data in a service local variable and check for existence before making the http call to the server. This solution is not bad but then you'll jave to implement a data cache handler to manage how long should your data live in the service.

other solution my least favorite is to implement something similar to #2 but use $rootScope instead and injected everywhere where you want to make your data accessible. this is not my recommendation, but would also work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.