我正在研究Hartl的教程学习足够的行动电缆,我已经坚持4.1节了。我复制并粘贴了教程中的代码以确保,并且带有data.content的弹出窗口仍然不会出现。
消息控制器:
.
.
def create
message = current_user.messages.build(message_params)
if message.save
ActionCable.server.broadcast 'room_channel',
content: message.content,
username: message.user.username
end
end
room_channel.rb:
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel"
end
def unsubscribed
end
end
routes.rb中:
Rails.application.routes.draw do
root 'messages#index'
resources :users
resources :messages
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
mount ActionCable.server, at: '/cable'
end
room.coffee:
App.room = App.cable.subscriptions.create "RoomChannel",
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) ->
alert(data.content)
本教程的其他任何部分都可以正常使用弹出窗口进行javascript警报。在我的服务器日志中,它说:
Started GET "/cable" for 127.0.0.1 at 2017-03-26 13:59:12 -0400
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2017-03-26 13:59:12 -0400
Successfully upgraded to WebSocket (REQUEST_METHOD: GET,HTTP_CONNECTION: keep-alive, Upgrade, HTTP_UPGRADE: websocket)
RoomChannel is transmitting the subscription confirmation
RoomChannel is streaming from room_channel
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2017-03-26 14:06:26 -0400
RoomChannel stopped streaming from room_channel
Started GET "/messages" for 127.0.0.1 at 2017-03-26 14:06:26 -0400
Processing by MessagesController#index as HTML
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Message Load (0.2ms) SELECT "messages".* FROM "messages" ORDER BY "messages"."created_at" DESC LIMIT ? [["LIMIT", 50]]
Rendering messages/index.html.erb within layouts/application
Rendered messages/_messages.html.erb (0.6ms)
Rendered messages/_message_form.html.erb (2.0ms)
Rendered messages/index.html.erb within layouts/application (4.5ms)
Rendered layouts/_logo.html.erb (0.4ms)
Rendered layouts/_header.html.erb (2.0ms)
Completed 200 OK in 71ms (Views: 36.4ms | ActiveRecord: 1.5ms)
答案 0 :(得分:1)
我遇到了同样的问题。
您还可以看到该消息正在广泛传播但未在客户端收到,即room.coffee
所以问题是CoffeeScript没有正确的打开和关闭括号。所以它适用于适当缩进的想法。
当您从网络上复制代码时,缩进不正确。
在以下代码中,请确保received: data
之后只有2个空格:
received: (data) ->
alert(data.content)
警告声明应该与开头有两个空隙。
此外,connected
和received
之类的功能也应该是App.room = App.cable.subscriptions.create "RoomChannel",
行
最后整体代码应如下所示:
App.room = App.cable.subscriptions.create "RoomChannel",
connected: ->
disconnected: ->
received: (data) ->
alert(data.content)
确保使用空格而非TAB