如何在Angular服务中获取$ stateParams

时间:2014-06-08 05:42:52

标签: javascript angularjs angularjs-service angular-ui-router

这是我的state定义:

.state('sub-topic',{
    url:"/topics/:topicId",
    templateUrl: "templates/sub-topics.html",
    controller: "SubTopicsController"
})

这是我的service

myApp.service('subTopicsService',function($http, $stateParams){

    this.getSubTopics = function(){
        $http.get('topics/' + $stateParams.topicId + '.json').success(function(data, status, header, config) {
             return data;
        });
    }
})

controller的一部分,'subTopicService'已注入

$scope.topicList = subTopicsService.getSubTopics();

问题是,服务中的$stateParamsundefined。 具体来说,我收到此错误消息:Cannot access property :topicId of undefined. 如何在我的服务中使用$stateParams

1 个答案:

答案 0 :(得分:0)

此方案应该有效。有一个有效的plunker。我所做的改变:

我刚刚重新构建了服务定义:

myApp.service('subTopicsService', function($http, $stateParams) {

  var getSubTopics = function() {
    $http.get('topics/' + $stateParams.topicId + '.json ')
      .success(function(data, status, header, config) {
        return data;
      });
  };
  // to prove, that this service can work with $stateParams
  var getStateParams = function() {
    return $stateParams;
  };

  return {
    getSubTopics: getSubTopics,
    getStateParams: getStateParams,
  };
});

这里我们将服务注入到控制器中:

myApp.controller('SubTopicsController', function($scope, $state, subTopicsService) {

  $scope.stateParams = subTopicsService.getStateParams();
});

这是我们的观点,消耗所有:

$stateProvider
    .state('sub-topic', {
      url: "/topics/:topicId",
      //templateUrl: "templates/sub-topics.html",
      template: '<div><pre>{{stateParams}}</pre></div>',
      controller: "SubTopicsController",
    });

有关更多详细信息,请参阅正常工作plunker