【问题标题】:How to keep a connection with a channel that uses paramaters passed from client to server for ActionCable?如何与使用从客户端传递到服务器的 ActionCable 参数的通道保持连接?
【发布时间】:2018-10-16 10:44:25
【问题描述】:

我不明白actioncable。我想让用户订阅一个看起来像这样的PostChannel

class PostNotificationsChannel < ApplicationCable::Channel

  def subscribed
    stream_from params[:post_id]
  end

  def unsubscribed
    stop_all_streams
  end
end

然后我有 js

/javascripts/channels/post_notifications.js

$(document).on('turbolinks:load', function() {
  $("a.post_subscribe").click(function subscribeToPost() {
  var post_id = $(this).parents("li").attr("class").split(" ")[0]; // Get the post id off the page
  App.post_notifications = App.cable.subscriptions.create({channel: "PostNotificationsChannel", post_id: post_id}, {

    connected: function() {},

    disconnected: function() {},

    received: function(data) {}
    });
  });
});

因此,您单击 .post_subscribe 锚标记,它会获取我在页面上拥有的那个帖子 HTML 类的值,然后在订阅创建的 params 哈希中使用它。这一切都很好,而且当该帖子发生某些操作时,单击它的用户将获得更新。但是,如果您刷新页面,则该连接无法将该消费者与该帖子重新连接,因为散列中没有参数。所以,我想知道如何摆脱这种情况。

此外,即使在 rails 指南页面上,它也会显示此 here 所以他们正在传递参数但是当页面重新加载时如何保持连接?

【问题讨论】:

    标签: javascript ruby-on-rails actioncable


    【解决方案1】:

    所以我从您的问题中了解到,当用户点击“订阅”链接时,您希望用户成为该帖子的关注者。为此,您必须通过在用户和作为关注者的帖子之间建立关联来将此信息存储在数据库中。 然后,每当该帖子上发生活动时,向该特定帖子的所有关注者的通知流广播通知。

    创建一个 NotificationsChannel,每个用户在登录网站时都会订阅该频道,例如,ID 为 1 的用户登录后,他将订阅一个通知流,该通知流对于每个用户都是唯一的,例如notify_user_1_channel

    class NotificationsChannel < ApplicationCable::Channel
      def subscribed
        if params[:recepient].present?
          stream_from "notify_#{params[:recepient]}_channel"
        end
      end
    
      def unsubscribed
        # Any cleanup needed when channel is unsubscribed
      end
    end
    

    在您的频道脚本中,

    App.chat = App.cable.subscriptions.create {
                channel: "NotificationsChannel"
                recepient: $('#recepient').data("recepient")
                }
    

    为了将接收者作为参数,在某处查看代码,最好在页脚中,

    <div id="recepient" data-recepient="User_<%= current_user.id %>"></div>
    

    并且,为了将通知广播到流中,在通知模型的 after_create_commit 中,

    ActionCable.server.broadcast "notify_#{notification.recepient_type}_#{notification.recepient_id}_channel"
    

    【讨论】:

    • O I C,非常好。我正在尝试以其他方式鼓起勇气,但我知道您的目标是什么。给我一些时间来标记为正确?
    • 当然,如果您发现任何其他方式,请随时通知我。所以我应该在下一个项目中尝试一下。
    • 我不认为有其他方法,看起来这就是动作电缆的工作原理。感谢您的澄清!
    • 你能给出这个代码吗?我看不到如何在 broadcast_to() 调用中将广播发送给用户。例如,第一个参数需要是用户订阅的频道。那么,当用户实际订阅并存储在数据库中时,如何获取用户?
    • 谢谢。 @Saqib Shahzad 昨晚我脑子里想了想,意识到我可以像上面那样使用我现有的 NotificationsChannel,但是,谢谢你发布上面的代码。作为注释,您可以使用 stream_from "notifications_#{current_user.id}" 如果您已将其设置为标识符,则可以节省您来回传递用户 ID
    猜你喜欢
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2018-06-18
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多