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

3

我定义了一个简单的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个回答

4
您可以使用 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的联合类型。您可以在Elm指南中了解联合类型


1

还有withDefault可供快速检查。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接