Router resolve will not inject into controller

前端 未结 2 642
走了就别回头了
走了就别回头了 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:15

    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:

    Demo

提交回复
热议问题