如何从响应中提取多个键的数据。在榆树
How to extract data of the multiple keys from the Response. in ELM
我正在尝试从 API 响应中提取数据,但在 decodeData 中,我只能传递一个解码字段,如果我试图传递多个字段,则会出错
Function get
is expecting the 2nd argument to be:
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 response is
{
firstName : "user",
lastName : "hero",
gender : "male"
}
如果数据定义为
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)
我正在尝试从 API 响应中提取数据,但在 decodeData 中,我只能传递一个解码字段,如果我试图传递多个字段,则会出错
Function
get
is expecting the 2nd argument to be: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 response is
{
firstName : "user",
lastName : "hero",
gender : "male"
}
如果数据定义为
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)