如何使用javascript向我们所有订阅的websocket连接发送全局消息而无需 channel 等(例如actioncable默认向所有打开的连接全局发送的ping消息)?
最佳答案
据我所知,你不能在没有 channel 的情况下直接从 JavaScript 中做到这一点(它需要先通过 Redis)。
我建议您将其作为正常的发布操作执行,然后在 Rails 中发送消息。
我会做这样的事情:
JavaScript:
$.ajax({type: "POST", url: "/notifications", data: {notification: {message: "Hello world"}}})
Controller :
class NotificationsController < ApplicationController
def create
ActionCable.server.broadcast(
"notifications_channel",
message: params[:notification][:message]
)
end
end
channel :
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_from("notifications_channel", coder: ActiveSupport::JSON) do |data|
# data => {message: "Hello world"}
transmit data
end
end
end
听 JavaScript:
App.cable.subscriptions.create(
{channel: "NotificationsChannel"},
{
received: function(json) {
console.log("Received notification: " + JSON.stringify(json))
}
}
)
关于ruby-on-rails - Rails 5 Actioncable 没有 channel 的全局消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48193506/