简体   繁体   English

在单个控制器angular js中有多个http请求

[英]Multiple http request in a single controller angular js

I have created different drupal views to create multiple json endpoints for multiple http request using angular. 我创建了不同的drupal视图以使用angular为多个http请求创建多个json端点。 In my angular script I have created multiple controller for each http request as shown below. 在我的角度脚本中,我为每个http请求创建了多个控制器,如下所示。 But I want to do multiple http request in single controller. 但是我想在单个控制器中执行多个http请求。 I have got inclination that $q and promises or factory are way forward but not completely sure. 我倾向于$ q和promises或factory是前进的方向,但不能完全确定。 Any help will be much appreciated. 任何帮助都感激不尽。 Thanks 谢谢

var module = angular.module('main',[]);
module.directive("masonry", function () {
    var NGREPEAT_SOURCE_RE = '<!-- ngRepeat: ((.*) in ((.*?)( track by (.*))?)) -->';
    return {
        compile: function(element, attrs) {
            // auto add animation to brick element
            var animation = attrs.ngAnimate || "'masonry'";
            var $brick = element.children();
            $brick.attr("ng-animate", animation);

            // generate item selector (exclude leaving items)
            var type = $brick.prop('tagName');
            var itemSelector = type+":not([class$='-leave-active'])";

            return function (scope, element, attrs) {
                var options = angular.extend({
                    itemSelector: itemSelector
                }, scope.$eval(attrs.masonry));

                // try to infer model from ngRepeat
                if (!options.model) {
                    var ngRepeatMatch = element.html().match(NGREPEAT_SOURCE_RE);
                    if (ngRepeatMatch) {
                        options.model = ngRepeatMatch[4];
                    }
                }

                // initial animation
                element.addClass('masonry');

                // Wait inside directives to render
                setTimeout(function () {
                    element.masonry(options);

                    element.on("$destroy", function () {
                        element.masonry('destroy')
                    });

                    if (options.model) {
                        scope.$apply(function() {
                            scope.$watchCollection(options.model, function (_new, _old) {
                                if(_new == _old) return;

                                // Wait inside directives to render
                                setTimeout(function () {
                                    element.masonry("reload");
                                });
                            });
                        });
                    }
                });
            };
        }
    };
});
angular.module('main',[]).controller('blogcontroller', function ($scope,$http) {
  $http.get('/blog-filter').success(function(result){
    $scope.blog = ( function () {
       return result.nodes;
    })();
  });
});


angular.module('cs',[]).controller('cscontroller', function ($scope,$http) {
  $http.get('/case-study-view').success(function(results){
    $scope.cs = ( function () {
      return results.nodes;
    })();
  });
});

Yes you should have your $http methods in a factory: 是的,您应该在工厂中使用$ http方法:

angular
  .module('sharedServices')
  .factory('blogRepository', blogRepository);

blogRepository.$inject = ['$http', '$q'];

function blogRepository($http, $q) {
  var service = {
    getBlogFilter: getBlogFilter
  };

  return service;

  function getBlogFilter() {
    var deferred = $q.defer();
    $http.get('/blog-filter').success(function(result){
      deferred.resolve(result);
    });
    return deferred.promise;
  }
}

and in your controller: 并在您的控制器中:

blogRepository.getBlogFilter().then(function(data) {
  $scope.blog = data.nodes;
});

It would be similar for the other $http call. 其他$ http调用也是如此。

Create a factory with all $http services and use $q like this: 使用所有$ http服务创建工厂,并使用$ q像这样:

(function(){
    app.factory('CountriesServices', countriesServices);
    countriesServices.$inject = ['$http', '$q', 'settings'];

function countriesServices($http, $q, settings) {
    var self = {};

    self.getCountries= function(){
        var deferred = $q.defer();
        var url = settings.baseService + 'api/country';

        $http.get(url)
            .success(deferred.resolve)
            .error(deferred.reject);

        return deferred.promise;
    };

    self.getCountry = function(id){
        var deferred = $q.defer();
        var url = settings.baseService + 'api/country/' + id;

        $http.get(url)
            .success(deferred.resolve)
            .error(deferred.reject);

        return deferred.promise;
    };



    return self;
}
})();

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

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