如何从Response中提取多个键的数据。在ELM

时间:2018-02-20 06:54:40

标签: http response elm

我正在尝试从API响应中提取数据但是在decodeData中我只能传递一个Decoded字段,如果我试图传递多个字段则会出错

  

函数get期望第二个参数为:

Decode.Decoder a
    type Msg = 
  FindData |
  ReqCbk ( Result Http.Error String )

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
  case msg of
    FindData -> 
      ( model, getData model.topic )

    ReqCbk ( Ok newData) ->
      ( { model | firstName = newData, err = ""}, Cmd.none )

    ReqCbk ( Err r ) ->
      ( { model | err = (toString r)}, Cmd.none )

getData : String -> Cmd Msg
getData topic =
  let
    url =
      "http://localhost:9191/"++topic++"/v1/xyz"

    request =
      Http.get url decodeData
  in
    Http.send ReqCbk request

decodeData : Decode.Decoder String
decodeData = 
   Decode.field "firstName" Decode.string

使用此方法我只能更新firstName,但我想更新完整的用户数据。

  

API响应

{
firstName : "user",
lastName : "hero",
gender : "male"
}

1 个答案:

答案 0 :(得分:1)

如果数据定义为

type alias Data =
    { firstName : String
    , lastName : String
    , gender : String
    }

然后您可以像这样定义解码器:

decodeData : Decode.Decoder Data
decodeData = 
    Decode.map3 Data
        (Decode.field "firstName" Decode.string)
        (Decode.field "lastName" Decode.string)
        (Decode.field "gender" Decode.string)