Elm中的序列Http.get [英] Sequence Http.get in Elm
问题描述
下面有一个按钮
,它试图加载远程内容...
Below I have a button
that attempts to load remote content ...
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不允许我按字符串搜索。 不允许
This is a valid Elm program, only there's one little problem: The API doesn't allow me to search by string. This is not allowed
/posts?author=amelia => Malformed Request Error
但是,允许此
/posts?author=2 => [ {...}, {...}, ... ]
所以我必须 first 首先获取作者以获取其 id
,然后然后我可以使用作者的ID来获取帖子...
So I must first fetch an author to get his/her id
, and then I can fetch posts using the author's id...
/author?name=amelia => { id: 2, name: "amelia", ... }
/posts?author=2
如何在下一个请求之后排序一个请求?理想情况下,我想将作者缓存在模型中的某个位置,以便我们只请求以前从未见过的作者。
How can I sequence one request after the next? Ideally I'd like to cache the authors somewhere in the model so we're only requesting ones that we haven't seen before.
推荐答案
您可以使用 Task.andThen
将两个任务链接在一起。假设 / posts
响应中包含作者ID,则可以在处理响应时将该作者ID添加到模型中。
You can use Task.andThen
to chain two tasks together. Assuming that the /posts
response includes the author ID, you can then add that author ID into you model when you handle the response.
Search s ->
let
getAuthor =
Author.decode
|> Http.get ("/author?name=" ++ s)
|> Http.toTask
getPosts author =
(Decode.list Post.decode)
|> Http.get ("/posts?author=" ++ author.id)
|> Http.toTask
cmd =
getAuthor
|> Task.andThen getPosts
|> Task.attempt PostsReceived
in
( model, cmd )
在 https://ellie-app.com/DBJc6Kn3G6a1 进行了编译
这篇关于Elm中的序列Http.get的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!