无法从React前端上的ActionCable访问数据

时间:2019-03-21 14:44:21

标签: javascript ruby-on-rails reactjs websocket actioncable

我正在尝试使用actioncable从rails后端广播属于某个游戏的消息。

在我的messages_controller中:

  def create
@game = Game.find(message_params[:game_id])
@message = Message.new(message_params)
if @message.save
  serialized_data = ActiveModelSerializers::Adapter::Json.new(
    MessageSerializer.new(@message)
  ).serializable_hash
  MessagesChannel.broadcast_to @game, serialized_data
  head :ok
end
end

在我的messages_channel中:

  def subscribed
    @game = Game.find(params[:id][:game_id])
    stream_from @game
  end

在前端,我正在使用此文件:

import ActionCable from 'actioncable';
import { CABLE } from "../constants";

export default function MessagesSubscription(
  game_id,
  { onUpdate = () => {} } = {}
) {
  // 2. Define our constructor
  this.cable = ActionCable.createConsumer(CABLE);
  // this.channel;
  this.game_id = game_id;
  this.onUpdate = onUpdate;

  // 3. Define the function we will call to subscribe to our channel
  this.subscribe = () => {
    console.log("subscribed")
    this.channel = this.cable.subscriptions.create(
      { channel: 'MessagesChannel', id: this.game_id },
      {
        connected: this.connected,
        disconnected: this.disconnected,
        received: this.received,
        rejected: this.rejected,
      }
    );
  };

  // 4. Define our default ActionCable callbacks.
  this.received = (data) => {
    console.log(`Received Data: ${data}`);

    this.onUpdate(data);
  };

  this.connected = () => {
    console.log(`this.connected`);
  };

  this.disconnected = () => {
    console.warn(`this.disconnected.`);
  };

  this.rejected = () => {
    console.warn('I was rejected! :(');
  };
}

问题在于,在客户端,我可以连接,断开和拒绝,但是我不能单击已接收。

在运行服务器和客户端时,如果查看终端中的rails后端,则会看到以下内容:

  

MessagesChannel正在发送订阅确认   MessagesChannel从#开始播放   在2019-03-21 10:29:09 -0400开始获取127.0.0.1的``/ api / v1 / cable''   在2019-03-21 10:29:09获得127.0.0.1的“ / api / v1 / cable /” [WebSocket]   -0400已成功升级到WebSocket(REQUEST_METHOD:GET,HTTP_CONNECTION:升级,HTTP_UPGRADE:websocket)无法执行   来自{{“ command” =>“ subscribe”的命令,   “ identifier” =>“ {\” channel \“:\” MessagesChannel \“,\” game_id \“:\” 15 \“}”})   [NoMethodError-未定义方法[]' for nil:NilClass]: /Users/flatironschool/Development/code/Flatiron/mod5/project/deep_forest_api/app/channels/messages_channel.rb:3:in 已订阅'| |   /Users/flatironschool/.rvm/gems/ruby-2.6.1/gems/actioncable-5.2.2.1/lib/action_cable/channel/base.rb:179:in block in subscribe_to_channel' | /Users/flatironschool/.rvm/gems/ruby-2.6.1/gems/activesupport-5.2.2.1/lib/active_support/callbacks.rb:109:in 中的run_callbacks块|   /Users/flatironschool/.rvm/gems/ruby-2.6.1/gems/activesupport-5.2.2.1/lib/active_support/execution_wrapper.rb:83:in   在“

”中wrap' | /Users/flatironschool/.rvm/gems/ruby-2.6.1/gems/actioncable-5.2.2.1/lib/action_cable/engine.rb:68:in 阻止(3个级别)

1 个答案:

答案 0 :(得分:0)

我在学校得到了TCF的帮助。

在我的消息频道中,我将其更改为:

  def subscribed
    @game = Game.find(params[:id][:game_id])
    stream_for @game
  end

因此,使用stream_for而不是stream_from。

此外,我还切换到使用npm包react-actioncable-provider。

我的客户端javascript在React中,如下所示:

import { ActionCable } from 'react-actioncable-provider';
import React, { Component, Fragment } from 'react';
import { CABLE, AUTH_HEADERS } from '../constants';
import { connect } from 'react-redux';
import Message from '../components/Message';

class Cable extends Component {

  render () {
    console.log("Cable.js")
    return (
      <Fragment>
        <ActionCable
          key={this.props.game_id}
          channel={{ channel: "MessagesChannel", game_id: this.props.game_id }}
          onReceived={(data) => console.log("handleReceived: ", data)}
        />
    </Fragment>
    )
  }
}

const mapStateToProps = state => {
  return { state }
}

const mapDispatchToProps = dispatch => {
  return {
    getMessages: data => dispatch({ type: "LOAD_MSGS", payload: data })
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Cable);

我现在可以从ActionCable接收和回复。