Elm 0.17:初始化时的 HTTP 请求

Elm 0.17: HTTP request on init

我已经按照 this blog post to make an HTTP call when I click a button. I would like to load that data on init, like 问了,但是那里给出的解决方案对我和我的代码略有不同来说不够清楚。

应用更新和初始化代码:

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 调用?

你的init应该是

init : (Model, Cmd Msg)
init =
  ( initialModel, Cmd.map ArticleListMsg ArticleList.fetchArticles )

ArticleList.fetchArticles 的类型为 Cmd ArticleList.Msg。您需要使用 Cmd.map 使用 ArticleListMsg 类型构造函数将该值映射到类型 Cmd Msg