2017-10-07 21 views
1

내 앱은 flags를 통해 localstorage에서 init 모델 값을 가져옵니다. 모델에 새 키를 추가했는데 플래그를 통해 전달 된 값의 누락 된 키 ("bar")로 인해 Elm 앱을 시작하는 동안 오류가 발생합니다. 앞으로 더 많은 새로운 키가 추가 될 수 있고, 그것이 발생할 때마다 localstorage를 지우고 싶지 않다는 것을 고려할 때, 플래그에 누락 된 키가있을 때 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>