繁体   English   中英

在同一页面上多次需要相同数据的自定义指令

[英]Custom Directive multiple times on same page requiring same data

我有一个自定义指令,该指令将使用2个不同的数据集放在2个不同位置的同一页上,但是所有数据都通过一个服务调用返回。 如何进行一次API调用并在指令的两个实例中使用数据?

您可以在第一次调用服务后从服务中返回一个承诺。 因此,这两个指令都可能调用service.getData().then(directiveCallback)但该服务仅从服务器获取一次数据。 在服务中,类似:

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

在任何情况下,都应始终由一种服务来处理,使用哪种服务以及如何使用它取决于您的应用程序,其中两种使用服务的方式是

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。 我更喜欢这一点,因为它从维护数据中抽象了您的指令和服务。

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.

我最不喜欢的另一种解决方案是实现类似于#2的方法,但改用$ rootScope并注入到要使数据可访问的所有位置。 这不是我的建议,但也可以

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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