【问题标题】:Multiple instances of directive, wait for $http calls to complete指令的多个实例,等待 $http 调用完成
【发布时间】:2017-07-26 14:50:06
【问题描述】:

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

 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 服务。

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

【问题讨论】:

    标签: angularjs


    【解决方案1】:
    app.service('Auth', function($http) {
       var promise;
    
       this.authorize = function() {
           if (!promise) {
             promise = $http.post('/myauth/...');
           }
    
           return promise;
       }
    });
    

    【讨论】:

    • 这很有趣,我搜索了一个小时的方法来做到这一点。一旦你发布了这个,我就遇到了这个问题,它提出了类似的建议:stackoverflow.com/a/35902375/1426342 这很有效,所以我接受这个作为答案。事后似乎很明显!哈哈!
    【解决方案2】:

    您应该使用 Promise 使其同步工作。 https://docs.angularjs.org/api/ng/service/$q

    函数提交(数据){

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

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多