【发布时间】:2017-11-15 05:40:27
【问题描述】:
试图让 elm 端口工作以维持会话。
在 index.html 中,脚本包含以下监听器:
window.addEventListener("load", function(event) {
app.ports.onSessionChange.send(localStorage.session);
}, false);
localStorage.session 看起来像这样(在我注销之前它一直存在):
{"email":"user@fake.com","token":"eyJhbG...","user_id":1,"handle":"me"}
Ports.elm中的定义是:
port onSessionChange : (Value -> msg) -> Sub msg
此端口在此处连接到Main.elm(如果我忘记包含以下一些定义,请告诉我):
subscriptions : Model -> Sub Msg
subscriptions model =
Ports.onSessionChange sessionChange
sessionChange : Json.Decode.Value -> Msg
sessionChange value =
let
result =
Json.Decode.decodeValue sessionDecoder value
in
case result of
Ok sess ->
SetSession (Just sess)
Err err ->
SetSession Nothing
...
type alias Session =
{ email : String
, token : String
, user_id : Int
, handle : String
}
...
import Json.Decode as Decode exposing (..)
import Json.Decode.Pipeline as Pipeline exposing (decode, required)
sessionDecoder : Decode.Decoder Session
sessionDecoder =
Pipeline.decode Session
|> Pipeline.required "email" Decode.string
|> Pipeline.required "token" Decode.string
|> Pipeline.required "user_id" Decode.int
|> Pipeline.required "handle" Decode.string
...
type Msg
= NoOp
| SetSession (Maybe Session)
...
update msg model =
case msg of
SetSession session ->
case Debug.log "session = " session of
Just sess ->
({ model | session = sess } , Cmd.none)
Nothing ->
(model, Cmd.none)
Debug.log "session" 在页面加载时在控制台中显示Nothing,因此 JS 正在与 elm 对话,但解码器似乎失败了。有什么想法吗?
【问题讨论】:
-
您确定
localStorage.session在javascript 中实际上是有效的吗?这个reduction of your code 工作正常 -
你成功了,我将会话保存为 JSON 字符串而不是 JSON。它在我使用
app.ports.onSessionChange.send(JSON.parse(localStorage.session));时有效。如果您将此作为答案,我将标记为正确。
标签: elm json-deserialization elm-port