如何在elm中显示结果类型的Html结果?

时间:2016-12-29 20:07:34

标签: elm

我已经定义了一个简单的serverResponse来模拟从api到elm-lang解析的响应。

我遇到问题从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 个答案:

答案 0 :(得分:2)

您可以使用case语句提取解码结果。这允许您明确地处理解码器的成功和失败。

您的main功能可以更改为以下内容(请注意,我已重新定义toList,因为您没有返回有效的Html):

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是一个带有两个构造函数的联合类型:OkErr。您可以阅读union types in the Elm Guide

答案 1 :(得分:0)

还有withDefault用于快速检查

Result.withDefault 0 (String.toInt "123") == 123