2016-12-29 8 views
0

私は単純なserverResponseを定義して、elm-langのapiからの応答をシミュレートしました。elmのResult typeからHtml結果を表示するには?

Resultから情報のHTMLを表示する問題が発生しています。

これを行うにはどのような方法が最適ですか?

import String exposing (..) 

import String exposing (..) 
import List exposing (..) 

import Result exposing (map) 

import Json.Decode as Json exposing (..) 

type alias Team = 
    { department : String 
    , names: List String 
    } 

serverResponse = 
    """ 
    [{"department":"product","names":["bob","sally","george"]},{"department":"marketing","names":["billy","diane","anita"]},{"department":"sales","names":["howard","steve","isha"]}] 
    """ 

stringDecoder = 
    Json.list Json.string 

infoDecoder : Json.Decoder Team 
infoDecoder = 
    Json.map2 Team 
     (Json.field "department" Json.string) 
     (Json.field "names" stringDecoder) 

teamDecoder : Json.Decoder (List Team) 
teamDecoder = 
    Json.list infoDecoder 

toList team = 
    p [] [ 
    team.department 
    ] 

transformList teams = 
     toList teams 

main = 
    Json.decodeString teamDecoder serverResponse 
    |> toString 
    |> text 

答えて

2

caseステートメントを使用して、デコードの結果を抽出することができます。これにより、デコーダの成功と失敗の両方を明示的に処理することができます。

あなたmain機能は(あなたが有効なHTMLを返していなかったので、私はtoListを再定義していることに注意してください)次のように変更することができます:

toList : Team -> Html msg 
toList team = 
    p [] [ text team.department ] 

main = 
    case Json.decodeString teamDecoder serverResponse of 
     Ok teams -> 
      div [] (List.map toList teams) 

     Err msg -> 
      text ("ERROR: " ++ msg) 

Resultは、2つのコンストラクタを持つ共用体型です:OkErrunion types in the Elm Guideにお読みください。

0

withDefault

Result.withDefault 0 (String.toInt "123") == 123 
クイックチェックのためにもあります
関連する問題