【问题标题】:Can't decode session from elm port无法从 elm 端口解码会话
【发布时间】: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


【解决方案1】:

我已将您的代码插入minimal working example,一切正常。您可能希望从 javascript 部分中记录 localStorage.session 的值,以确保它是有效的 JSON 值。

【讨论】:

  • 如 OP cmets 中所述,我的 JS 返回的是 JSON 字符串,而不是实际的 JSON。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
相关资源
最近更新 更多