Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 指令的多个实例,等待$http调用完成_Angularjs - Fatal编程技术网

Angularjs 指令的多个实例,等待$http调用完成

Angularjs 指令的多个实例,等待$http调用完成,angularjs,Angularjs,我有一个简单的指令,根据$http调用的响应,在元素/属性上转移ng if以隐藏它: app.directive('showFor', [ 'authorizationService', function(authorizationService) { return { restrict: 'EA', template: '<show-for-transclude ng-if="show"></show-

我有一个简单的指令,根据$http调用的响应,在元素/属性上转移ng if以隐藏它:

 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;
                        });
                }
            }
        };
    }
]);
authorizationService调用获取当前用户所属组的列表,并将其缓存在会话存储中。这非常有效,除了当页面上有许多这样的指令时,它会在第一个指令返回并缓存结果之前多次调用$http服务


我的问题是,有没有办法告诉指令的多个实例的后续调用等待第一个调用的响应?

您应该使用promise使其同步工作$q

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

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

       return promise;
   }
});
函数提交数据{

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

有趣的是,我花了一个小时来寻找答案。当你发布这篇文章时,我遇到了一个类似的问题:这很有效,所以我接受这个作为答案。这在事实发生后似乎是显而易见的!哈哈!