ui-router resolve with dynamic parameters

AngularjsAngular UiAngular Ui-Router

Angularjs Problem Overview


This is probably simple but I can't find anything in the docs and googling didn't help. I'm trying to define a state in $stateProvider where the URL I need to hit on the server to pull the needed data depends on a state URL parameter. In short, something like:

 .state('recipes.category', {
    url: '/:cat',
    templateUrl: '/partials/recipes.category.html',
    controller: 'RecipesCategoryCtrl',
    resolve: {
      category: function($http) {
        return $http.get('/recipes/' + cat)
          .then(function(data) { return data.data; });
      }
    }
  })

The above doesn't work. I tried injecting $routeParams to get the needed cat parameter, with no luck. What's the right way of doing this?

Angularjs Solutions


Solution 1 - Angularjs

You were close with $routeParams. If you use ui-router use $stateParams instead. This code works for me:

.state('recipes.category', {
    url: '/:cat',
    templateUrl: '/partials/recipes.category.html',
    controller: 'RecipesCategoryCtrl',
    resolve: {
         category: ['$http','$stateParams', function($http, $stateParams) {
             return $http.get('/recipes/' + $stateParams.cat)
                    .then(function(data) { return data.data; });
         }]
     }
})

Solution 2 - Angularjs

For those who are using ui-router 1.0 $stateParams is deprecated, you should use $transition$ object instead:

.state('recipes.category', {
    url: '/:cat',
    templateUrl: '/partials/recipes.category.html',
    controller: 'RecipesCategoryCtrl',
    resolve: {
         category: ['$http','$transition$', function($http, $transition$) {
             return $http.get('/recipes/' + $transition$.params().cat)
                    .then(function(data) { return data.data; });
         }]
     }
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionklironView Question on Stackoverflow
Solution 1 - AngularjsRetoView Answer on Stackoverflow
Solution 2 - AngularjsG07chaView Answer on Stackoverflow