简体   繁体   中英

How do I obtain $stateParams in Angular service

Here is my state definition:

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

Here is my service

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

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

A part of my controller , that has 'subTopicService' injected

$scope.topicList = subTopicsService.getSubTopics();

The problem is, the $stateParams is undefined in the service. Specifically I get this error message: Cannot access property :topicId of undefined. How do I use $stateParams in my service?

This scenario should work. There is a working plunker . Changes I made:

I just restructred the service definition:

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,
  };
});

Here we get the service injected into controller:

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

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

And here is our view, consuming that all:

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

See the working plunker for more detauls

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM