我需要在我的 Rails API(仅)应用程序中使用 Websocket。页面没有任何服务器端渲染。该应用程序是 Angular 和 Xamarin 的纯 JSON 后端。我看到很多教程在 Rails 中使用 coffescript 作为 ActionCable 客户端,但这不是我的情况。
问题是:如何在 Rails 的 coffescript 之外仅将 ActionCable 用作 API,例如用于 Android、iOS、Angular 和 React 客户端?
我找到了不同且有用的资源,但我仍然有点困惑。
1:ActionCable usage for Rails API - 这似乎是最好的,但是我怎样才能找到 ActionCable 框架交换的所有 JSON 命令?
2:Similar Question to the mine
3:Rails API Websocket GEM - 好吧,不是ActionCable,但这个家伙已经将coffescript编译成JS并移植到项目中。对移动开发没有用。
如果有不同的解决方案或更好的知识,请告诉我。我需要“破解”它才能让它工作。
编辑:我也发现了这个 repo action-cable-js但是如何整合呢?
最佳答案
API 的 Actioncable 只有官方支持,还有这个 npm package叫 actioncable
它使用仅使用 API 的方法分离了对与 actioncable 服务器通信的支持。
npm install actioncable
然后在你的 react /角度代码中import ActionCable from 'actioncable';
# create a connection with the actioncable server
# use ws:// for http and wss:// for https
const cable = ActionCable.createConsumer("ws://your-backend-server.com/cable");
# now you create a subscription
my_subscription = cable.subscriptions.create("MessengerChannel", {
connected: function() {
console.log("You've subscribed to the Messenger Channel");
},
disconnected: function() {
console.log("You've disconnected from the Messenger Channel");
},
received: function (received_data) {
# broadcast data from the Messenger channel is received here
console.log(received_data);
}
})
在后端,您需要安装 actioncable,为此请执行此操作# routes.rb file
Rails.application.routes.draw do
mount ActionCable.server => '/cable'
end
关于ruby-on-rails - Rails API 应用程序中 ActionCable 的 Websocket 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45784317/