生成新频道时,会注释掉stream_from方法调用。我理解,它适合识别流,例如stream_from" comments _#{message.id}"。
但是如果这个频道没有这样的目标并且应该流式传输所有评论?什么是此通道的默认行为(可能是值)而未指定stream_from?
答案 0 :(得分:1)
假设您的频道名为SomethingChannel
class SomethingChannel < ApplicationCable::Channel
def subscribed
# because you do not need stream_from, then remove the stream_from below
# stream_from "something_channel"
# and just immediately transmit the data. This should be a hash, and thus I use `as_json`; Change this accordingly as you see fit
transmit(Comment.all.as_json)
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
然后在客户端,您只需在需要时调用以下内容。
# ...coffee
App.cable.subscriptions.create 'SomethingChannel',
connected: ->
console.log('connected')
# Called when the WebSocket connection is closed.
disconnected: ->
console.log('disconnected')
# `transmit(Comment.all.as_json)` above will invoke this
received: (data) ->
console.log('received')
console.log(data)
您应该会在Google Chrome / Firefox控制台中看到以下内容:
connected
received
▼ [{…}]
▶ 0: {id: 1, title: "Hello ", content: "World from Earth! :)", created_at: "2018-02-13T16:15:05.734Z", updated_at: "2018-02-13T16:15:05.734Z"}
▶ 1: {id: 2, title: "Lorem ", content: "Ipsum Dolor", created_at: "2018-02-13T16:15:05.734Z", updated_at: "2018-02-13T16:15:05.734Z"}
length: 2
▶ __proto__: Array(0)
P.S。如果你不能使用stream_from
或stream_for
,那么也许你可能不需要ActionCable
,也许你最好从API中检索所有的评论相反(即GET /comments
)