Angular JS TypeError:无法读取路由上未定义的属性“id”

Angular JS TypeError: Cannot read property 'id' of undefined on Route

本文关键字:未定义 属性 id 路由 TypeError JS 读取 Angular      更新时间:2023-09-26

我正在学习一些AngularJS,我遇到了一个绊脚石。我可以检索我的 jSON 并将其输入前端,但是当我要转到新视图时,我的问题就来了。我的 ID 无法正确输入。基本上,如果单击我的项目 ID 为 1,则其显示 id 为 14。或者我收到类型错误:无法读取未定义的属性"14"

任何想法都会很有帮助。

jSON

[
    {
        "id": 14,
        "title": "new post",
        "excerpt": "EXCERPT",
        "content": "ushajsd"
    },
    {
        "id": 10,
        "title": "last post",
        "excerpt": "test",
        "content": "test"
    },
    {
        "id": 4,
        "title": "middle post",
        "excerpt": "contents to post",
        "content": "contents to post"
    },
    {
        "id": 1,
        "title": "Hello world!",
        "excerpt": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!",
        "content": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!"
    }
]

AngularJS

//Create main module
var module = angular.module('module', [''])
//Services
module.factory('posts', function($http) {
  return {
      getAsync: function(callback) {
          $http.get('/wp-content/themes/ajax/ajax.php').success(callback);
      }
  };
});
// Set up our mappings between URLs, templates, and controllers
function caseStudyConfig($routeProvider) {
  $routeProvider.
    when('/casestudy/:id', {
      controller: caseCtrl,
      templateUrl: '/wp-content/themes/templates/casestudy.php'
    }).
    otherwise({
      redirectTo: '/'
    });
}
// Set up our route so the service can find it
module.config(caseStudyConfig);
//Controllers
function homeCtrl (posts, $scope) {
  posts.getAsync(function(data) {
       $scope.content = data;
  });
}
function caseCtrl (posts, $scope, $routeParams) {
  posts.getAsync(function(data) {
       $scope.content = data[$routeParams.id];
  });
}

假设getAsync回调中的数据属性是您发布的 JSON 的表示形式,我认为这是因为您尝试通过对象在数组中的位置而不是其 id 属性来访问对象。如果您使用的是下划线/lodash,您可以像这样轻松解决此问题:

function caseCtrl (posts, $scope, $routeParams) {
  posts.getAsync(function(data) {
       // Find the object with id which matches id in route params
       $scope.content = _.findWhere(data, { id: $routeParams.id });
  });
} 

或者,您可以编写自己的循环来从集合中检索正确的对象:

function caseCtrl (posts, $scope, $routeParams) {
  posts.getAsync(function(data) {
       $scope.content = getObjectById(data, $routeParams.id);
  });
  function getObjectById(collection, id) {
    for (var i = 0, obj; i < collection.length; i ++) {
        obj = collection[i];
        if (obj.id === id) {
            return obj;
        }
    }
    return null;
  }
}