我正在探索ELM并试图访问web api。我跟着这个link。
我可以点击我的服务并获得响应(显示在浏览器网络选项卡中),但失败代码部分正在从elm更新执行。
实施
---Model
type alias Model =
{
message : String,
}
model:Model
model = {
message = "Hello"
}
--update
postRequest : Http.Request
postRequest =
{ verb = "POST"
, headers =
[("Content-Type", "application/json")
]
, url = "http://xyz/events/list"
, body = Http.string """{ "domainId": 1 }"""
}
getEventList: Cmd Msg
getEventList =
Task.perform Messages.FetchFail Messages.FetchSucceed (Http.fromJson decodeString (Http.send Http.defaultSettings postRequest))
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Messages.NoOp ->
( model, Cmd.none )
Messages.FetchSucceed xy->
({model| message = "success"},Cmd.none)
Messages.FetchFail _->
({model |message = "fail"} ,Cmd.none)
API响应:
{ "message": "", "data": [
{
"eventId": 104,
"title": "private Events",
"description": "abc",
"businessId": 51,
"businessTitle": "VampireDA_Adda",
"startDate": "2016-07-08"
},
{
"eventId": 107,
"title": "Event weekly Midnight",
"description": "xyz",
"businessId": 44,
"businessTitle": "Spanish Scotch",
"startDate": "2016-07-08"
}] }
如果我执行了任何错误,请帮助我。
以及如何将json解码为模型(用响应json填充模型)?
答案 0 :(得分:3)
你可能会收到错误,因为解码没有成功。但首先要尝试习惯管道
Http.send Http.defaultSettings postRequest
|> Http.fromJson decodeString
|> Task.perform Messages.FetchFail Messages.FetchSucceed
解码需要榆树记录
type alias DataItem =
{ eventId: Int
, title: String
, description : String
, businessId : Int
, businessTitle : String
, startDate: String
}
解码器看起来像
dataDecoder =
object6 DataItem
("eventId" := int)
("title" := string)
("description" := string)
("businessId" := int)
("businessTitle" := string)
("startDate" := string)
decoder = at ["data"] (list dataDecoder)
解码器需要一些习惯,因此我创建了一个网站来帮助您练习:http://simonh1000.github.io/decoder/