Elm 0.17:init上的HTTP请求

时间:2016-12-29 19:42:42

标签: elm

单击按钮后,我跟着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调用?

1 个答案:

答案 0 :(得分:2)

您的init应该是

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

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