如何使用 ActionCable 作为 API [英] How to use ActionCable as API

查看:50
本文介绍了如何使用 ActionCable 作为 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Rails 5 beta 1 和 ActionCable 构建了一个非常简单的应用程序,以显示用户何时上线并让他们相互发送消息.

I built a very simple app using Rails 5 beta 1 and ActionCable to show when users come online and let them send messages to each other.

现在,我基本上想采用 ActionCable 的客户端部分,在另一个应用程序的上下文中实现它(在 Rails 5 上运行)并将其与第一个应用程序连接发送和接收数据(例如用户的在线状态或消息).

Now, I would basically like to take the client-side part of ActionCable, implement it in the context of another app (that does not run on Rails 5) and connect it with the first app to send and receive data (such as the online status of users or messages).

要从第二个应用程序发送数据,我假设我可以简单地发出 AJAX POST 请求.问题是:如何从我的第二个应用订阅第一个应用的开放连接?

To send data from that second app, I assume, I can simply make an AJAX POST request. The question is: How do I subscribe from my second app to an open connection of the first app?

甚至:如何通过 API 从另一个应用程序订阅我的 Rails 应用程序的 ActionCable 连接?

Or even: How do I subscribe to the ActionCable connection of my Rails app from another app via API?

我的猜测是,我基本上想在我的第二个应用程序中以某种方式包含这个咖啡脚本:

My guess is, I essentially want to include this coffeescript somehow in my second app:

App.appearance = App.cable.subscriptions.create "AppearanceChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    # ...

推荐答案

虽然 mwalsher 的解决方案对我非常有帮助,但我最近在 Rails 存储库上发现了一个 pull request,其中包含对我的问题的官方解决方案.

While mwalsher's solution was extremely helpful to me, I recently found a pull request on the Rails repository with an official solution to my question.

https://github.com/rails/rails/pull/24991

我想,在不久的将来,这将被添加到主要文档中.这是官方 actioncable npm 包的链接:https://www.npmjs.com/package/actioncable

I assume, in the near future this will be added to the main documentation. Here is the link to the official actioncable npm package: https://www.npmjs.com/package/actioncable

您可以在任何 JS 应用程序中使用类似于 mwalsher 的解决方案.只需安装 npm 包:

You can use it similar to mwalsher's solution with any JS app. Just install the npm package:

npm install actioncable --save

这里是文档中的 JS 示例:

Here the JS example from the documentation:

ActionCable = require('actioncable')

var cable = ActionCable.createConsumer('wss://RAILS-API-PATH.com/cable')

cable.subscriptions.create('AppearanceChannel', {
  // normal channel code goes here...
});

拉取请求已经合并了一段时间,现在描述是官方的一部分自述文件 - 只是还没有出现在 Rails 指南中.

The pull request has been merged for a while, now and the description is part of the official Readme - just not yet in the Rails Guides.

这篇关于如何使用 ActionCable 作为 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆