【问题标题】:load data from service before controllers在控制器之前从服务加载数据
【发布时间】:2014-04-08 08:40:19
【问题描述】:

您好,我想在加载任何控制器之前从工厂加载数据。我找到了一种使用解析的方法:

angular.module('agent', ['ngRoute','ui.bootstrap','general_module', 'order_module','customer_module']).config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/customer', {
    templateUrl: 'customer_module/partials/customer.php',
    resolve:{
      'MyServiceData':function(loginvalidation){
        // MyServiceData will also be injectable in your controller, if you don't want this you could create a new promise with the $q service
       var a=loginvalidation.check_usertype();
      }}
    }
    );
  $routeProvider.otherwise({redirectTo: '/customer'});
}]);

但问题是我必须在每条路线上都复制它。 angularjs有没有办法在启动任何控制器之前编写一次代码以加载服务(不复制我的代码)?

谢谢

【问题讨论】:

标签: javascript angularjs angularjs-directive angularjs-service angularjs-routing


【解决方案1】:

我做的一件事是在我的控制器功能中,我在根级别没有任何代码。只有函数声明。见这里:

angular.module('app').controller('TestCtrl',function($scope){

    //no code here at root level, except for some init call
    init();

    function init(){
        //some init code
        service.getSomeData().then(function(data){
            //Tell your controller to run here
            $scope.dataLoaded = true;
            doSomethingWithData(data);
        });
    }

    function addSomeWatch(){
        //some watch code here
    }

    function foo(bar){
        //something crazy
    }
});

这取决于您的服务是否调用所有返回承诺,无论如何他们都应该这样做。

angular.module('app').factory('TestService', function(){

    return {
        getSomeData : function(){
            var d = $q.deferred();
            $http.get('someurl')
                .then(function(resp){
                    d.resolve(resp);
                });
            return d.promise;
        }
    }

});

【讨论】:

    猜你喜欢
    • 2013-08-30
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    相关资源
    最近更新 更多