Most optimize way to load datas to display on router's controller

I need to build a User that can be the resut of different REST API call (each way comes from a specific route).

Let's say for this example that we can visit:

  • http://myapp/#user/:pseudo
  • http://myapp/#user/:user_id

    angular.module('Test').config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/user/:pseudo', {
                    templateUrl: 'views/user.html',
                    controller: 'userFromPseudoCtrl'
                }).
                when('/user/:user_id', {
                    templateUrl: 'views/user.html',
                    controller: 'userFromIdCtrl'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }
    ]);
  • then, i have 3 different controllers:

  • userFromPseudoCtrl
  • userFromIdCtrl
  • userCtrl (To control the view)

    angular.module('Test').controller('userFromPseudoCtrl', function($User, $http) {
        $http.get('/getUserFromPseudo/test')
        .success(function(User) {
             $User.set(User);
        });
    });
    
    angular.module('Test').controller('userFromIdCtrl', function($User, $http) {
        $http.get('/getUserFromId/test')
        .success(function(User) {
             $User.set(User);
        });
    });
    
    angular.module('Test').controller('userCtrl', function($scope, $User) {
        $scope.User = $User;
    });
  • This way is not good because the userCtrl is called before the $http callback (from the router's controllers), so the User is actually empty into the page (i was hopping it will be automatically updated).

    Before i try to manage with it (using $rootScope.$apply() ), i am wondering what is the more optimize way to do this kind of process (loading datas from router's controller then display it).

    Do you use as many controllers as i do ? Do you process these REST APIs calls in the same controller that "bind" your view ? I am interesting to know !


    When you define your routes you can define an additional value named resolve which is an object where each field is a promise that when resolved will be injected into your controller:

    Route Definition:

    when('/user/:pseudo', {
        templateUrl: 'views/user.html',
        controller: 'userFromPseudoCtrl'
        resolve: {dataNeeded: userPseudoService.getUserData()});
    

    Service ( new ):

    angular.module('Test').service('userPseudoService', function($http){
        return $http.get('/getUserFromPseudo/test');
    });
    

    Controller:

    angular.module('Test').controller('userFromPseudoCtrl', function(dataNeeded){});
    

    The route will not change until the promise is resolved.

    链接地址: http://www.djcxy.com/p/13594.html

    上一篇: AngularJS路由导致404

    下一篇: 大多数优化方式来加载数据以显示在路由器的控制器上