2016-10-09 57 views
1

我想從這個URL JSON數據列表:https://raw.githubusercontent.com/raywenderlich/recipes/master/Recipes.json榆樹 - 獲取JSON列表數據

我不明白在這種情況下

... 
main = 
    App.program 
    { init = init 
    , view = view 
    , update = update 
    , subscriptions = \_ -> Sub.none 
    } 

-- MODEL 

type alias Model = 
    { name : String 
    , imageURL: String 
    } 

init = 
    (Model "" "", Cmd.none) 

-- UPDATE 

type Msg 
    = Recipes 
    | FetchSucceed (List Model) 
    | FetchFail Http.Error 

update msg model = 
    case msg of 
    Recipes -> 
     (model, fetchRecipes) 

    FetchSucceed recipe -> 
     (recipe, Cmd.none) 

    FetchFail _ -> 
     (model, Cmd.none) 


-- VIEW 

view model = 
    div [] 
    [ ul [] (List.map getItem model) 
    ] 


getItem item = 
    li [] [ text item.name ] 

-- HTTP 

fetchRecipes = 
    let 
    url = 
     "https://raw.githubusercontent.com/raywenderlich/recipes/master/Recipes.json" 
    in 
    Task.perform FetchFail FetchSucceed (Http.get decodeListRecipes url) 


decodeRecipes = 
    Json.object2 Model 
    ("name" := Json.string) 
    ("imageURL" := Json.string) 

decodeListRecipes = 
    Json.list decodeRecipes 

做,但我不斷收到這個錯誤:

Function `program` is expecting the argument to be: 
    { ..., 
     update : 
     Msg 
      -> { imageURL : String, name : String } 
      -> ({ imageURL : String, name : String }, Cmd Msg) , 
     view : { imageURL : String, name : String } -> Html Msg 
    } 

But it is: 
    { ... 
    , update : Msg -> List Model -> (List Model, Cmd Msg) 
    , view : List { a | name : String } -> Html b 
    } 

回答

1

FetchSucceed標籤被定義爲具有的模型(FetchSucceed (List Model))名單,但在你的update功能你TREA把它看作是一個單一的模型而不是一個列表。如果我將值改爲複數,應該強調的問題區域:

FetchSucceed recipes -> 
    (recipes, Cmd.none) 

不知道究竟你想達到什麼目的,我只能在一個潛在的解決方案提供了一個暗示,比如,如果你只是想借此列表的第一個元素,依傍着當前模式,如果沒有返回的食譜,你可以做這樣的事情:

FetchSucceed recipes -> 
    let recipe = 
     case List.head recipes of 
      Just r -> r 
      Nothing -> model 
    in 
     (recipe, Cmd.none) 
+0

感謝乍得的幫助我想通了以後,我需要在「init」函數中將配方製作在列表中 – kayne