Search code examples
angularjsangular-ui-routerstateresolve

inject resolve into toParams on $stateChangeStart


I have a config file which contains a state that looks like the following:

$stateProvider.state('home', {
    url: '?data',
    abstract: true,
    resolve: {
        data: ['MyModel', '$stateParams', function (MyModel, $stateParams) {
            return MyModel.getData($stateParams);
        }]
    }
});

and then a module file that looks like this:

App.module.run(['$rootScope', '$state', function ($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams) {

where toParams would return object{data:undefined}. I know that the resolve works and should have data. How do I correctly pass the resolve from my state into the $stateChangeStart and then access it?

I have tried injecting my data resolve manually into my module file, but it returns undefined. I have tried setting the params attribute to see if that was the way to go:

resolve: {
        data: ['MyModel', '$stateParams', function (MyModel, $stateParams) {
            return MyModel.getData($stateParams);
        }]
    },
params: { 
    'foo':'bar', // this would be available in toParams 
    'data': //can i put my data here? 
}

Solution

  • You should simply be able to inject MyModel into your run function, and read it the same way you read it inside your resolve process. Example run function (assumes your getData function returns a promise):

    App.module.run(function($rootScope, MyModel) {
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
            // get the same data your resolve is using (you can also pass in toParams or the like)
            MyModel.getData(toParams).then(function(data){
                // do something with your data here inside $stateChangeStart
            });
        });
    });
    

    This is what makes injection great, you simply inject something when you want to use it.