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

查看:129
本文介绍了如何将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上运行 not ),并将其与第一个应用程序连接发送和接收数据(例如用户或消息的在线状态).

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信息库中找到了一个拉取请求,其中包含我问题的正式解决方案.

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

您可以将其与mwalsher的解决方案类似地用于任何JS应用程序.只需安装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...
});

编辑:拉取请求已经合并了一段时间,该描述属于官方

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天全站免登陆