Drupal 8 - 从控制器获取当前节点 ID

Drupal 8 - Get current node id from controller

我正在使用 reactjs 构建一个 Drupal 8 模块,我需要从控制器获取当前节点 ID,以便我可以根据节点 ID 执行某些任务,但我总是收到一个空值,我的路由工作正常我的功能如下:

  public function currentNodeId()
    {
        // get current node
        $node_id = \Drupal::routeMatch()->getParameter('node')->Id();

        return new JsonResponse(
            array(
                'node_id' => $node_id
            )
        );
    }

在 mymodule.routing.yml 我有:

 mymodule-currentNode:
   path: '/mymodule/currentNodeId'
   defaults:
     _controller: '\Drupal\mymodule\Controller\MyModuleController::currentNodeId'
     _title: 'Current node id'
   requirements:
     _permission: 'access content'

我可以从我的模块文件中获取当前节点 ID 'mymodule.module' 与我在 currentNodeId 函数中所做的相同:

   $node_id = \Drupal::routeMatch()->getParameter('node')->Id();

有人知道这是某种安全措施还是我做错了什么?谢谢

我通过在每次加载模块时将当前节点 ID 存储在一个变量中来解决这个问题。您必须禁用模块缓存,以便每次都能加载 .module 文件。

更多信息在这里:https://drupal.stackexchange.com/questions/229780/get-current-node-id-from-controller/229787#229787