2016-12-29 5 views
0

ボタンをクリックすると、this blog postをフォローしてHTTPコールを発信しました。私はthis question asksのようにinitにそのデータをロードしたいのですが、そこに書かれている解決策は私と私のわずかに異なるコードのために十分ではありません。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呼び出しは 'Cmd.none'ではなく'(Model、Cmd Msg) 'のinitの' Cmd'部分に置きます。だから 'init =(initModel、fetchArticles)'? – toastal

答えて

2

あなたinitCmd ArticleList.Msgを入力

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

ArticleList.fetchArticlesていなければなりません。 Cmd.mapを使用して、ArticleListMsg型のコンストラクタを使用して、その値をCmd Msgにマップする必要があります。

関連する問題