我正在尝试从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"
}
答案 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)