Router resolve will not inject into controller

前端 未结 2 638
走了就别回头了
走了就别回头了 2021-01-01 02:47

I have tried everything to get ui-router\'s resolve to pass it\'s value to the given controller–AppCtrl. I am using dependency injection with $inject, and that

2条回答
  •  死守一世寂寞
    2021-01-01 03:21

    Here is how I work with resolve. It should receive promise. So I create service accordingly.

    app.factory('User', function($http){
        var user = {};
        return {
            resolve: function() {
                return $http.get('api/user/1').success(function(data){
                    user = data;
                });
            },
            get: function() {
                return user;
            }
        }
    });
    

    This is main idea. You can also do something like this with $q

    app.factory('User', function($q, $http){
        var user = {};
        var defer = $q.defer();
    
        $http.get('api/user/1').success(function(data){
            user = data;
            defer.resolve();
        }).error(function(){
            defer.reject();
        });
    
        return {
            resolve: function() {
                return defer.promise;
            },
            get: function() {
                return user;
            }
        }
    });
    

    These are almost identical in action. The difference is that in first case, service will start fetching date when you call resolve() method of service and in second example it will start fetch when factory object is created.

    Now in your state.

    $stateProvider.state('app.index', {
      url: '/me',
      templateUrl: '/includes/app/me.jade',
      controller: function ($scope, $rootScope, User) {
        $scope.user = User.get();
        console.log($scope.user);
      },
      controllerAs: 'vm',
      resolve: {
        auser: function(User) {
          return User.resolve()
        }
      }
    });
    

提交回复
热议问题