UI-router, use stateparams in service

前端 未结 2 1764
长发绾君心
长发绾君心 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:44

    The issue I see here is that you are trying to access the $stateParams before the state is ready. There are several events that happen when changing states.

    First is $stateChangeStart where you are notified of the state you are changing to and coming from as well as all of the params in both states.

    After this, the resolve starts to happen. The resolve in your case is calling a function that uses $stateParams

    After everything is resolved and good (no rejections or errors), and just prior to the $stateChangeSuccess event, the state params are updated in the $stateParams object.

    Basically, you cannot access the params for the state you are changing to via the $stateParams object until after the state change is completed. This is done in case the state change is rejected and cannot be changed. In this case, the previous state remains and the previous state's params will be in $stateParams.

    As a quick work-around, you can use the $stateChangeStart event to access the toParams (the params for the state you are changing to) and put them somewhere ($rootScope, or a service) so you can access them when you need them.

    Here is a quick example with $rootScope

    .run(['$rootScope', function($rootScope){
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            $rootScope.toParams = toParams;
        });
    }]);
    
    .factory('CategoryLoader',['$rootScope', 'Category', '$q',
      function($rootScope, Category, $q){
        return function(){
          var delay = $q.defer();
          Category.get({cat_id: $rootScope.toParams.id}, // <-- notice its using the object we put in $rootScope, not $state or $stateParams
            function(category){
              delay.resolve(category);
            },
           function(){
             //delay.reject('Unable to fetch category ' + $state.params.cat_id)
          });
          return delay.promise;
        }
    }]);
    

    Also, I believe your resource is not setup to correctly use the id you are passing. You were using cat_id above, in order to link it to the :id of the URL, you would have to map it as `{id: '@cat_id'}

    factory('Category', function($resource){
        return $resource('/api/category/byId/:id/', {id: '@cat_id'});
    });
    

提交回复
热议问题