单击按钮后,我跟着this blog post进行了HTTP调用。我想在init
上加载这些数据,就像this question所要求的那样,但是那里给出的解决方案对我来说还不够清楚,而且代码略有不同。
应用更新和初始代码:
init : (Model, Cmd Msg)
init =
( initialModel, Cmd.none )
-- UPDATE
type Msg
= ArticleListMsg ArticleList.Msg
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
ArticleListMsg articleMsg ->
let (updatedModel, cmd) = ArticleList.update articleMsg model.articleListModel
in ( { model | articleListModel = updatedModel }, Cmd.map ArticleListMsg cmd )
ArticleList update 代码:
module ArticleList exposing (..)
-- UPDATE
type Msg
= NoOp
| Fetch
| FetchSucceed (List Article.Model)
| FetchFail Http.Error
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
NoOp ->
(model, Cmd.none)
Fetch ->
(model, fetchArticles)
FetchSucceed articleList ->
(Model articleList, Cmd.none)
FetchFail error ->
case error of
Http.UnexpectedPayload errorMessage ->
Debug.log errorMessage
(model, Cmd.none)
_ ->
(model, Cmd.none)
-- HTTP calls
fetchArticles : Cmd Msg
fetchArticles =
let
url = "/api/articles"
in
Task.perform FetchFail FetchSucceed (Http.get decodeArticleFetch url)
我已尝试在init
而不是Cmd.none
上发送命令:
init : (Model, Cmd Msg)
init =
( initialModel, ArticleList.Fetch )
但是编译器抱怨道:
The type annotation is saying:
( Model, Cmd Msg )
But I am inferring that the definition has this type:
( Model, ArticleList.Msg )
我也试过传递这个功能:
init =
( initialModel, ArticleList.fetchArticles )
但是编译器抱怨道:
Cannot find variable `ArticleList.fetchArticles`.
30| ( initialModel, ArticleList.fetchArticles )
^^^^^^^^^^^^^^^^^^^^^^^^^
`ArticleList` does not expose `fetchArticles`.
如何发送正确的消息以在init上进行HTTP调用?
答案 0 :(得分:2)
您的init
应该是
init : (Model, Cmd Msg)
init =
( initialModel, Cmd.map ArticleListMsg ArticleList.fetchArticles )
ArticleList.fetchArticles
的类型为Cmd ArticleList.Msg
。您需要使用Cmd.map
将该值映射到使用Cmd Msg
类型构造函数键入ArticleListMsg
。