2016-12-29 71 views
0

我按照this blog post进行HTTP调用,当我点击一个按钮。我想加载init上的数据,就像this question所要求的那样,但是给出的解决方案对我和我稍微不同的代码来说都不够清楚。Elm 0.17:初始化HTTP请求

应用程序更新和init代码:

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

也许看看这个简化的例子https://github.com/rofrol/elm-route-url/blob/simplify/examples/elm-architecture-tutorial/MainWithFullUrl.elm – rofrol

+0

这是0.17的代码。 Http模块有很多重大更改。 – toastal

+0

你把你最初的Http调用放在'(Model,Cmd Msg)'的init的'Cmd'部分,而不是'Cmd.none'。所以'init =(initModel,fetchArticles)'? – toastal

回答

2

init应该

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

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