UI-router, use stateparams in service

前端 未结 2 1765
长发绾君心
长发绾君心 2021-01-19 14:34

I have this state:

  .state(\'admin.category\',{
    url: \'/category\',
    templateUrl:\'views/admin.category.html\',
    resolve:{
      category: [\'Cate         


        
2条回答
  •  广开言路
    2021-01-19 14:45

    console.log is by reference and asynchronous

    • If you see it in the console it's because the state already became activated.
    • resolve happens before a state is activated , so $state.current.params is still not available at that phase.
    • See: Javascript unexpected console output with array assignment;

    UPDATE

    I looked inside the source code, It looks like $stateParams that is injected into resolve functions is a local copy and not the global $stateParams. The global $stateParams is also updated only after the state is activated.

    Also the state URL should contain the parameter: url: '/category/:id',

    From $stateParams Service docs:

    $stateParams Service:

    As you saw previously the $stateParams service is an object that will have one key per url parameter. The $stateParams is a perfect way to provide your controllers or other services with the individual parts of the navigated url.

    Note: $stateParams service must be specified as a state controller, and it will be scoped so only the relevant parameters defined in that state are available on the service object.

    So I guess you must do something like this:

    State:

    .state('admin.category',{
      url: '/category',
      templateUrl:'views/admin.category.html',
      resolve:{
        category: ['CategoryLoader','$stateParams', function(CategoryLoader, $stateParams){
          return CategoryLoader($stateParams);
        }]
      },
    })
    

    Factory:

    .factory('CategoryLoader',['Category', '$q',
      function(Category, $q) {
        return function($stateParams){
          var delay = $q.defer();
          Category.get({cat_id:$stateParams.id},
            function(category){
              delay.resolve(category);
            },
           function(){
             //delay.reject('Unable to fetch category ' + $stateParams.cat_id)
          });
          return delay.promise;
        }
    }]);
    

提交回复
热议问题