0

I have a simple directive that transcludes an ng-if on its element/attribute to hide it based on the response from an $http call:

 app.directive('showFor',
[
    'authorizationService', function(authorizationService) {
        return {
            restrict: 'EA',
            template: '<show-for-transclude ng-if="show"></show-for-transclude>',
            transclude: true,
            scope: { process: '@' },
            link: function(scope, element, attrs, ctrl, transclude) {
                var process = scope.process || attrs.process;

                if (!_.isUndefined(attrs.showFor) && !_.isEmpty(attrs.showFor)) {
                    process = attrs.showFor;
                    authorizationService
                        .Authorize(process)
                        .then(function(result) {
                            scope.show = result;
                        });
                }
            }
        };
    }
]);

The authorizationService call gets a list of groups that the current user is a member of and caches it in session storage. This works great except when there are many of these directives on a page it calls the $http service a bunch of times before the first one returns and caches the results.

My question is, is there a way to tell subsequent calls from multiple instances of a directive to wait for the response of the first call?

Brandon
  • 830
  • 1
  • 15
  • 35

2 Answers2

1
app.service('Auth', function($http) {
   var promise;

   this.authorize = function() {
       if (!promise) {
         promise = $http.post('/myauth/...');
       }

       return promise;
   }
});
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38
  • Its funny, I searched for an hour on a way to do this. And as soon as you posted this I ran across this question which suggested something similar: https://stackoverflow.com/a/35902375/1426342 This worked so I am accepting this as the answer. Which seems blatantly obvious after the fact! hah! – Brandon Jul 26 '17 at 15:10
0

You should use promise to make it work synchronous. https://docs.angularjs.org/api/ng/service/$q

function submit(Data) {

        var deferred = $q.defer();
        $http({
            method: "POST",
            url: "/YourAPI/Method",
            data: Data
        })
       .then(function (response) {
           deferred.resolve(response);

       }).catch(function (error) {
           deferred.reject(error);
       });
        return deferred.promise;
    }
Sagar Hani
  • 146
  • 2
  • 8