首页 > 解决方案 > 角度参数 $routeParams 和 http.get params 方法不起作用

问题描述

我正在尝试仅使用前端来构建博客网站。我的博客数据在 api 中。我已经构建了博客提要,其中使用 angularjs get 方法显示了不同博客的列表。但是对于博客的详细视图,我需要从 api 获取单个博客数据结果。我已经尝试过使用 $routeParams 选项。但它没有奏效。我的博客 api 有 id 参数,它返回特定 blogid 的博客数据。请帮我解决这个问题。

blogdetail.html(模板)

<div>
  <div><h1>Blog Details</h1></div>

  <div ng-repeat="xr in blog">
    {{xr.BLOGID}}

  <div>
</div>

blogController.js(控制器)

'use strict';
app.controller('blogController', ['$scope','$http', function ($scope, $http, $routeParams) {
    $http.get('http://example.com/api/blog/', {
        params: {id: $routeParams.id}
    })
       .then(function(res){
          $scope.blog = res.data;
        }).catch(function(response) {
        console.log("ERROR:", response);
    });
}]);

route 网站的博客详细信息部分的提供者

$routeProvider
    .when("/Blog/:id", {
        controller : "blogController" ,
        templateUrl : "views/BlogDetail.html"
    })

这是我得到的错误 - TypeError: Cannot read property 'id' of undefined

标签: angularjs

解决方案


你需要在函数中需要的函数之前添加数组中的所有参数,否则它们没有定义。

问题就在这里['$scope','$http', function

'use strict';
    app.controller('blogController', ['$scope','$http', '$routeParams', function ($scope, $http, $routeParams) {
        $http.get('http://example.com/api/blog/', {
            params: {id: $routeParams.id}
        })
           .then(function(res){
              $scope.blog = res.data;
            }).catch(function(response) {
            console.log("ERROR:", response);
        });
    }]);

推荐阅读