我只创建了一个Rails 5 API,我需要创建一个实时的web通知。
通过使用ActionCable可以做到这一点吗?是否有人有行动电缆或任何其他解决方案的例子?
提前谢谢。
发布于 2016-10-27 15:02:51
这是一个web通知通道,允许您在向右流广播时触发客户端web通知:
创建服务器端web通知通道:
# app/channels/web_notifications_channel.rb
class WebNotificationsChannel < ApplicationCable::Channel
def subscribed
stream_for current_user
end
end
创建客户端web通知通道订阅:
# app/assets/javascripts/cable/subscriptions/web_notifications.coffee
# Client-side which assumes you've already requested
# the right to send web notifications.
App.cable.subscriptions.create "WebNotificationsChannel",
received: (data) ->
new Notification data["title"], body: data["body"]
从应用程序的其他地方将内容广播到web通知通道实例:
# Somewhere in your app this is called, perhaps from a NewCommentJob
WebNotificationsChannel.broadcast_to(
current_user,
title: 'New things!',
body: 'All the news fit to print'
)
WebNotificationsChannel.broadcast_to
调用在当前订阅适配器的pubsub队列中为每个用户设置一个单独的广播名称下的消息。对于ID为1的用户,广播名为web_notifications:1
。
https://stackoverflow.com/questions/40272066
复制相似问题