简体   繁体   中英

Custom Directive multiple times on same page requiring same data

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM