【发布时间】:2018-02-19 15:42:18
【问题描述】:
我有一个 react 前端(不使用 react-rails gem),我想使用 Rails api 进行实时交互。我的rails 中有这个post.coffee 代码已经在为ActionCable 工作了:
App.post = App.cable.subscriptions.create "PostChannel",
connected: ->
disconnected: ->
received: (data) ->
console.log(data)
document.getElementById('test').innerHTML = data['message']
notify: (message) ->
@perform 'notify', message: message
还有这个 post_channel.rb
class PostChannel < ApplicationCable::Channel
def subscribed
stream_from "post_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def notify(data)
ActionCable.server.broadcast 'post_channel', message: data['message']
end
end
工作示例:
现在在我的反应应用程序中,假设在页面加载 [componentWillMount()] 时,我想从 post_channel.rb 中“调用”通知方法。我将如何做?我搜索了一些方法,看到这篇文章的接受答案:How to use ActionCable as API
所以在我的 react 应用程序的 componentWillMount() 生命周期中,我有以下代码:
componentWillMount() {
var cable = ActionCable.createConsumer('ws://localhost:8000/cable');
cable.server.broadcast 'post_channel', { message: 'ji'}
}
componentWillMount 中的代码甚至不调用我的 rails 应用程序中的 websocket。这个怎么做?我没有看到太多资源。或者你能推荐任何最适合 react-rails 堆栈的 websocket 库吗?
【问题讨论】:
标签: ruby-on-rails ruby reactjs websocket actioncable