ActionCable 从不建立与通道的连接

ActionCable never establishes connection to channel

我正在尝试获取第一个 ActionCable 示例 运行,但是,我觉得从客户端到通道的连接从未建立。对于此处未提及的所有其他内容,我几乎都遵循 edge guides

# app/channels/notifications_channel.rb
class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    byebug
    stream_from "notifications"
  end

  def unsubscribed
    stop_all_streams
  end

  def receive(data)
    ActionCable.server.broadcast("notifications", data)
  end
end

byebug 从未被调用过。我实际上可以在该文件中放入一堆语法乱码,并且不会在任何地方看到错误。就像文件从未加载过一样。

不过,这是 javascript,如果建立连接,我希望看到 "connected" 警报,但这种情况从未发生过。不过,文件已正确加载和执行,因为我可以在浏览器控制台中检查 App 变量,它会向我显示 App.notifications 作为有效的订阅对象(尽管它对调试没有多大帮助,因为大多数属性都是函数)。

// app/assets/javascripts/channels/notifications.js
App.notifications = App.cable.subscriptions.create("NotificationsChannel", {
  connected: function() {
    // Called when the subscription is ready for use on the server
    alert('connected');
  },

  disconnected: function() {
    // Called when the subscription has been terminated by the server
  },

  received: function(data) {
    alert(data)
    // Called when there's incoming data on the websocket for this channel
    $("#notifications").prepend(data.html);
  }
});

如果有帮助的话,我的 Puma 总是从 "Single mode" 开始,我不确定这是否是问题所在,也不确定如何解决。

所以这就是原因。我不知何故只是试图将所有内容设置为默认值,看看它是否会起作用,它确实起作用了。然后我通过慢慢添加配置和代码来找出真正的问题所在,这是 config/environments/development.rb:

中的以下行
config.reload_classes_only_on_change = false

将其设置为 true 解决了它。

我遇到了同样的问题,设置 config.reload_classes_only_on_change 没有帮助。

我需要按 turbolinks:load

包装频道代码
$(document).on("turbolinks:load", function() {
   // ...
   const channel = consumer.subscriptions.create(
     { channel: channel_name, ...other params },
     connected() {}, 
     disconnected() {}
   )
})