无法读取 null ember 的 属性 'id'

Cannot read property 'id' of null ember

我正在尝试使用 Ember 应用程序从 WordPress 应用程序中获取数据。我正在尝试获取 WordPress 中 ID 为“2”的菜单项。我正在使用 ember-wordpress 插件并且可以成功获取我的帖子,我只是在努力从 API.

中获取菜单

下面是我的菜单模型

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  count: DS.attr('number')
});

这是我的路线。

import Ember from 'ember';

export default Ember.Route.extend({

  model() {
    return Ember.RSVP.hash({
      menu: this.store.findRecord('menu', 2)
    });
  }

});

然而,当我尝试点击 URL 时,我在控制台中收到错误消息

Error while processing route: Cannot read property 'id' of null TypeError: Cannot read property 'id' of null

这是我从终点得到的 JSON。

{
"ID": 2,
"name": "Main Menu",
"slug": "main-menu",
"description": "",
"count": 2,
"items": [
{
"id": 19,
"order": 1,
"parent": 0,
"title": "Projects",
"url": "http://localhost:8888/ember-wp/projects/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 17,
"object": "page",
"object_slug": "projects",
"type": "post_type",
"type_label": "Page"
},
{
"id": 20,
"order": 2,
"parent": 0,
"title": "Services",
"url": "http://localhost:8888/ember-wp/services/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 15,
"object": "page",
"object_slug": "services",
"type": "post_type",
"type_label": "Page"
}
],
"meta": {
"links": {
"collection": "http://localhost:8888/ember-wp/wp-json/wp/v2/menus/",
"self": "http://localhost:8888/ember-wp/wp-json/wp/v2/menus/2"
}
}
}

谁能看出我哪里出错了?

我不知道你得到的错误,但第一个元素没有 'id' 字段,而是 'ID' 字段(大写)。

我想你正在使用 WP API Menus 插件来提取数据,因为我 运行 遇到了同样的问题。您将需要编辑该插件中的文件之一以更正此问题。

wp-api-menus-v2.php

  1. 在第 108 行,将 $rest_menus[ $i ]['ID'] = $menu['term_id']; 更改为 $rest_menus[ $i ]['id'] = $menu['term_id'];
  2. 在第 143 行,将 $rest_menu['ID'] = abs( $menu['term_id'] ); 更改为 $rest_menu['id'] = abs( $menu['term_id'] );

将这两个键从大写更改为小写即可解决您的问题。