$routeParams在angularjs中未定义

$routeParams gets undefined in angularjs?

本文关键字:未定义 angularjs routeParams      更新时间:2023-09-26

我正在调用一个json文件的http调用。在第一个控制器中,我得到类别,在第二个控制器中我得到具有特定ID的类别。

url会使用categoryid进行更新,但$routeParams显示为未定义,无法访问该文件。

这是我的代码:

$stateProvider.state('categories', {
  url: '/category',
  templateUrl: 'templates/categories.html',
  controller: 'CategoriesCtrl'
});
$stateProvider.state('postC', {
  url: '/category/:category',
  templateUrl: 'templates/postsc.html',
  controller: 'PostCtrl'
});

在控制器中,我有以下内容:

angular.module('myapp')
.controller('CategoriesCtrl', ['$scope', '$http',
  function($scope, $http) {
    $http.get("~/wp/v2/terms/category")
      .then(function(res) {
        $scope.categories = res.data;
      })
  }
])
.controller('PostCtrl', ['$scope', '$http', '$routeParams',
  function($scope, $http, $routeParams) {
    $http.get("~/wp/v2/terms/category/" + $routeParams.category).success(function(res) {
      $scope.current_category_id = $routeParams.category;
      console.log($routeParams.category);
      $scope.pageTitle = 'Posts in ' + res.data.name + ':';
      document.querySelector('title').innerHTML = 'Category: ' + res.data.name + ' | AngularJS Demo Theme';
      $http.get("~/wp/v2/posts/?filter[category_name]=" + res.data.name).success(function(res) {
        $scope.posts = res.data;
        console.log($scope.posts);
      })
    })
  }
]);

类别的视图如下:

<div class="list">
  <a ng-repeat="category in categories" href="#/category/{{category.id}}" class="item item-thumbnail-left">
    <h2>{{category.name}}</h2>
  </a>
</div>

当我点击类别时,URL变为:http://localhost:8100/#/category/12,但~/wp/v2/terms/category/" + $routeParams.category中的$stateparams.category未定义,因此http请求无法通过。

我想不出我错过了什么?

尝试在每个实例中将$routeParams更改为$stateParams。很明显,您使用的ui-router使用"状态",而ngRouter使用"路由"。

angular.module('myapp')
.controller('CategoriesCtrl', ['$scope', '$http',
  function($scope, $http) {
    $http.get("~/wp/v2/terms/category")
      .then(function(res) {
        $scope.categories = res.data;
      })
  }
])
.controller('PostCtrl', ['$scope', '$http', '$stateParams',
  function($scope, $http, $stateParams) {
    $http.get("~/wp/v2/terms/category/" + $stateParams.category).success(function(res) {
      $scope.current_category_id = $stateParams.category;
      console.log($stateParams.category);
      $scope.pageTitle = 'Posts in ' + res.data.name + ':';
      document.querySelector('title').innerHTML = 'Category: ' + res.data.name + ' | AngularJS Demo Theme';
      $http.get("~/wp/v2/posts/?filter[category_name]=" + res.data.name).success(function(res) {
        $scope.posts = res.data;
        console.log($scope.posts);
      })
    })
  }
]);

您可能需要仔细检查附近的代码

.controller('PostCtrl', ['$scope','$http','$rootScope', function($scope, $http, $routeParams)

应该是

.controller('PostCtrl', ['$scope','$http','$rootScope', '$routeParams', function($scope, $http, $rootScope, $routeParams)

在这里阅读更多关于创建控制器语法的信息。您缺少注射器。