【发布时间】:2016-12-29 19:42:42
【问题描述】:
当我单击一个按钮时,我已关注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 更新代码:
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.17 的代码。 Http 模块有很多重大变化。
-
您将初始 Http 调用放在 init 的
Cmd部分( Model, Cmd Msg )中,而不是Cmd.none。那么init = ( initModel, fetchArticles )? -
@rofrol 谢谢你。我看了一下,但它似乎没有回答我的问题。如果您有任何其他想法,我已经用我认为应该可以工作的代码和编译器错误更新了我的问题。
-
如果您使用 Cmd 打开,则不需要
Fetch。 Here 是我在 0.17 提交时编写的单文件完整 Elm 应用程序,并带有初始提取。
标签: elm