2017-10-07 37 views
1

我的應用程序通過標誌從localstorage獲取init模型值。我在模型中添加了一個新的鍵,並且由於通過標誌傳遞的值中缺少鍵(「bar」),所以在啓動Elm應用程序時會導致錯誤。考慮到將來可以添加更多的新密鑰,並且我不希望每次發生時都要清除本地存儲,有沒有辦法告訴Elm在標記中缺少密鑰時分配默認值?在Elm中正常處理標記中缺失的鍵

type alias Model = 
    { foo : String, bar : Int } 

update : msg -> Model -> (Model, Cmd msg) 
update _ model = 
    model ! [] 

view : Model -> Html msg 
view model = 
    text <| toString model 

main : Program Flags Model msg 
main = 
    Html.programWithFlags 
     { init = init 
     , update = update 
     , view = view 
     , subscriptions = always Sub.none 
     } 

HTML代碼

<body> 
    <script> 
    var app = Elm.Main.fullscreen({foo: "abc"}) 
    </script> 
</body> 

回答

3

下面是在榆樹鬆弛通道@ilias友好提供很好的解決方案。

https://ellie-app.com/mWrNyQWYBa1/0

module Main exposing (main) 

import Html exposing (Html, text) 
import Json.Decode as Decode exposing (Decoder) 
import Json.Decode.Extra as Decode --"elm-community/json-extra" 


type alias Model = 
    { foo : String, bar : Int } 


flagsDecoder : Decoder Model 
flagsDecoder = 
    Decode.map2 Model 
     (Decode.field "foo" Decode.string |> Decode.withDefault "hello") 
     (Decode.field "bar" Decode.int |> Decode.withDefault 12) 


init : Decode.Value -> (Model, Cmd msg) 
init flags = 
    case Decode.decodeValue flagsDecoder flags of 
     Err _ -> 
      Debug.crash "gracefully handle complete failure" 

     Ok model -> 
      (model, Cmd.none) 


update : msg -> Model -> (Model, Cmd msg) 
update _ model = 
    model ! [] 


view : Model -> Html msg 
view model = 
    text <| toString model 


main : Program Decode.Value Model msg 
main = 
    Html.programWithFlags 
     { init = init 
     , update = update 
     , view = view 
     , subscriptions = always Sub.none 
     } 

HTML

<body> 
    <script> 
    var app = Elm.Main.fullscreen({foo: "abc"}) 
    </script> 
</body>