How to pass $stateParams from ui-router to service in resolve? [closed]

偶尔善良 提交于 2019-12-09 16:42:57

问题


I have a route to retrieve a single post and a service to query my API to do so. But I need to pass parameters from the URL to the service so that I can call the API properly. I cannot wrap my head around how to do that.

This is what I have come up with so far. I left out what seemed not relevant for this question.

Thanks for your help!

The routing

myModule.config([
  '$stateProvider',
  '$urlRouterProvider',
  '$locationProvider',
  function($stateProvider, $urlRouterProvider, $locationProvider) {

    $stateProvider
      .state('post', {
        url: '/posts/:hash_id/:slug',
        templateUrl: '/js/app/views/post.html',
        controller: 'PostCtrl',
        resolve: {
          postPromise: ['posts', function(posts, $stateParams){
            //returns undefined
            console.log($stateParams);
            return posts.getOne($stateParams);
          }]
        }
      })
// etc

The service

myModule.factory('posts', ['$http', 'auth', function($http, auth){
  var o = {
    posts: [],
    post: {}
  };
  o.getOne = function(params) {
    // Returns undefined
    console.log(params);
    return $http.get('/api/v1/posts/' + params.hash_id).success(function(data){
      angular.copy(data, o.post);
    });
  };
  return o;
}])

回答1:


You missed to add $stateParams dependency in postPromise resolve

Code

postPromise: ['posts', '$stateParams', function(posts, $stateParams){


来源:https://stackoverflow.com/questions/31056881/how-to-pass-stateparams-from-ui-router-to-service-in-resolve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!