我正在尝试运行第一个ActionCable示例,但是,我觉得从客户端到通道从未建立连接。我几乎遵循了此处未提及的其他所有内容的边缘指南。
# 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
拜虫从未被召唤过。我实际上可以将一堆语法乱码放入该文件中,并且在任何地方都不会看到错误。就像文件从未加载一样。
不过这是javascript,如果它会建立连接,我希望看到"已连接"警报,但这永远不会发生。该文件已正确加载和执行,因为我可以在浏览器控制台中检查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 总是以"单一模式"启动,我不确定这是否可能是问题以及如何解决它。
所以这就是原因。我不知何故只是尝试将所有内容设置为默认值,看看它是否会起作用,它确实如此。然后,我通过慢慢添加配置和代码,找出了问题的实际所在,这是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() {}
)
})