AngularJS - Multiple Directive Instances making XHR call multiple times

浪子不回头ぞ 提交于 2019-12-05 10:26:08

First solution, probably the best one: don't make the call from the directive, which should just be a graphical element. Do the call from the controller, and pass the data as argument to both directives.

Second solution, use a service in the directive, and always return the same promise:

myModule.factory('myService', function($http) {
    var promise = null;
    var getData = function() {
        if (promise == null) {
            promise = $http.get(...).then(...);
        }
        return promise;
    };

    return {
        getData: getData
    };
});

The controller defines two Promise objects where each Promise object makes an Http GET request and returns the response.

Change to:

The SERVICE defines two Promise objects where each Promise object makes an Http GET request and returns the response.

The service then can remember that it has already done the GET(s) and just return their result every subsequent time it is asked for them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!