Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Router resolve will not inject into controller

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 seems to cause the issues. What am I missing?

Routing

$stateProvider.state('app.index', {
  url: '/me',
  templateUrl: '/includes/app/me.jade',
  controller: 'AppCtrl',
  controllerAs: 'vm',
  resolve: {
    auser: ['User', function(User) {
      return User.getUser().then(function(user) {
        return user;
      });
    }],
  }
});

Controller

appControllers.controller('AppCtrl', AppCtrl);

AppCtrl.$inject = ['$scope', '$rootScope'];

function AppCtrl($scope, $rootScope, auser) {
  var vm = this;
  console.log(auser); // undefined

  ...
}

Edit Here's a plunk http://plnkr.co/edit/PoCiEnh64hR4XM24aH33?p=preview

like image 642
derek_duncan Avatar asked Jan 13 '15 03:01

derek_duncan


1 Answers

When you use route resolve argument as dependency injection in the controller bound to the route, you cannot use that controller with ng-controller directive because the service provider with the name aname does not exist. It is a dynamic dependency that is injected by the router when it instantiates the controller to be bound in its respective partial view.

Also remember to return $timeout in your example, because it returns a promise otherwise your argument will get resolved with no value, same is the case if you are using $http or another service that returns a promise.

i.e

  resolve: {
    auser: ['$timeout', function($timeout) {
      return $timeout(function() {
        return {name:'me'}
      }, 1000);
    }],

In the controller inject the resolve dependency.

appControllers.controller('AppCtrl', AppCtrl);

AppCtrl.$inject = ['$scope', '$rootScope','auser']; //Inject auser here

function AppCtrl($scope, $rootScope, auser) {
  var vm = this;
  vm.user = auser;
}

in the view instead of ng-controller, use ui-view directive:

<div ui-view></div>

Demo

like image 64
PSL Avatar answered Nov 01 '22 03:11

PSL