下面我有一个button
尝试加载远程内容...
import Post exposing (Post)
import Html exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode as Decode
type alias Model =
{ posts : List Post }
type Msg
= Search String
| PostsReceived (Result Http.Error (List Post))
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Search s ->
let
cmd =
(Decode.list Post.decode)
|> Http.get ("/posts?author=" ++ s)
|> Http.send PostsReceived
in
( model, cmd )
PostsReceived (Ok posts) ->
{ model | posts = posts }
! []
PostsReceived (Err error) ->
( model, Cmd.none )
view : Model -> Html Msg
view model =
button
[ onClick (Search "amelia") ]
[ text "Read posts by Amelia" ]
这是一个有效的 Elm 程序,只有一个小问题:API 不允许我按字符串搜索。这是不允许的
/posts?author=amelia => Malformed Request Error
但是,这是允许的
/posts?author=2 => [ {...}, {...}, ... ]
所以我必须先获取一个作者来获取他/她id
,然后我可以使用作者的 id 获取帖子......
/author?name=amelia => { id: 2, name: "amelia", ... }
/posts?author=2
如何在下一个请求之后对一个请求进行排序?理想情况下,我想将作者缓存在模型中的某个位置,因此我们只请求我们以前从未见过的作者。