榆树 - 获取JSON列表数据

时间:2016-10-09 21:58:48

标签: elm

我正在尝试从此网址获取JSON数据列表:https://raw.githubusercontent.com/raywenderlich/recipes/master/Recipes.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 个答案:

答案 0 :(得分:1)

您的Digits.logIn().done(this.onLogIn.bind(this)).fail(this.onFail.bind(this)); 标记定义为包含模型列表(FetchSucceed),但在您的FetchSucceed (List Model)函数中,您将其视为单个模型而非列表。如果我将值更改为复数,则应强调问题区域:

update

在不确切知道你想要实现什么的情况下,我只能提供一个潜在解决方案的提示,例如,如果你只是想要获取列表的第一个元素并且如果没有配方则回退到当前模型回来了,你可以做这样的事情:

FetchSucceed recipes ->
    (recipes, Cmd.none)