如何将$ stateParams从ui-router传递给service in service?

时间:2021-08-25 12:29:55

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.

我有一个路由来检索单个帖子和一个服务来查询我的API这样做。但我需要将参数从URL传递到服务,以便我可以正确调用API。我无法理解如何做到这一点。

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 个解决方案

#1


11  

You missed to add $stateParams dependency in postPromise resolve

您错过了在postPromise解析中添加$ stateParams依赖项

Code

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

#1


11  

You missed to add $stateParams dependency in postPromise resolve

您错过了在postPromise解析中添加$ stateParams依赖项

Code

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