【问题标题】:Rails 5 API + Real time notificationsRails 5 API + 实时通知
【发布时间】:2016-10-26 21:03:29
【问题描述】:

我只创建一个 Rails 5 API,我需要创建一个实时网络通知。

这可以通过使用 ActionCable 实现吗?有没有人有 Action Cable 或任何其他解决方案的示例?

提前致谢。

【问题讨论】:

    标签: redis ruby-on-rails-5 rails-api actioncable


    【解决方案1】:

    这是一个网络通知通道,可让您在向正确的流广播时触发客户端网络通知:

    创建服务器端网络通知通道:

    # app/channels/web_notifications_channel.rb
    class WebNotificationsChannel < ApplicationCable::Channel
      def subscribed
        stream_for current_user
      end
    end
    

    创建客户端网络通知频道订阅:

    # 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"]
    

    将内容从应用程序的其他位置广播到网络通知通道实例:

    # 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。

    【讨论】:

      猜你喜欢
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2015-11-21
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 2016-02-27
      相关资源
      最近更新 更多