2017-07-27 81 views
1

我有message = %{"to" => "testuser", "value" => "asdads"}地圖。我需要訪問該地圖我如何獲取鳳凰仙丹框架內的地圖價值

message.to 
message[:to] 
Map.fetch!(message, to) 

沒什麼裏面工作「到」鍵的值爲止

這是控制檯的錯誤消息

[error] GenServer #PID<0.395.0> terminating 
** (KeyError) key :to not found in: %{"to" => "testuser", "value" => "aadadadad"} 
    (phoenix_chat) web/channels/room_channel.ex:31: PhoenixChat.RoomChannel.handle_in/3 
    (phoenix) lib/phoenix/channel/server.ex:225: anonymous fn/4 in Phoenix.Channel.Server.handle_info/2 
    (stdlib) gen_server.erl:601: :gen_server.try_dispatch/4 
    (stdlib) gen_server.erl:667: :gen_server.handle_msg/5 
    (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3 
Last message: %Phoenix.Socket.Message{event: "message:new", payload: %{"to" => "testuser", "value" => "aadadadad"}, ref: "4", topic: "room:Pamidu"} 
State: %Phoenix.Socket{assigns: %{user: "Pamidu"}, channel: PhoenixChat.RoomChannel, channel_pid: #PID<0.395.0>, endpoint: PhoenixChat.Endpoint, handler: PhoenixChat.UserSocket, id: nil, joined: true, pubsub_server: PhoenixChat.PubSub, ref: nil, serializer: Phoenix.Transports.WebSocketSerializer, topic: "room:Pamidu", transport: Phoenix.Transports.WebSocket, transport_name: :websocket, transport_pid: #PID<0.384.0>} 
+0

'消息[ 「到」]'? – Dogbert

+0

另外聲明sais'按摩'不''消息' –

回答

4

你的地圖上的鍵是字符串,而不是原子。您發佈的所有三個代碼片段都將訪問密鑰:to(原子),而不是"to"(字符串)。

您可以使用message["to"]來訪問該值。如果您想在該值不存在時發出錯誤,則還可以執行Map.fetch!(message, "to")

0

你可以做類似下面

case Map.fetch(message,"to") do 
    {:ok, value} -> IO.inspect value;   #Success 
    :error  -> IO.inspect "Key Not found" #Error 
end