刚从 Fable / Elmish / F# 开始,但在完成一个基本概念时遇到了困难......
代码的目标是执行一个简单的 HTTP GET 请求,然后在网页上将 GET 请求的结果发布给用户。想法是使用 FablePromise
或async
执行 GET 请求并返回结果,然后可以使用 Elmish 和 Fable 将结果显示在网页上。
我希望网页(本地主机)会输出一个包含 GET 请求响应的文本字符串,而不是我在网页上只得到“[object Promise]”。然而,GET 请求的所需响应会记录在浏览器控制台上。txt
如果我在 promise 的正文中(在 之前)发出 printfn 命令,return
我还可以在浏览器控制台中看到 GET 请求的结果。
因此:我不知道如何访问承诺的结果。请帮忙,我错过了什么?[Fable][1] 中的示例应用程序创建了一个图像“容器”,并根据 HTTP 获取的结果放置了一个图像,但我需要使用文本(json 字符串)。
这是我的代码:
module App
open Elmish
open Fable.React
open Elmish.React
open Fable.React.Props
open Fable.Import
open Fable.PowerPack
open Fetch
// CallAPI
let getMe = promise {
let! res = fetch "https://reqres.in/api/users/2" []
let! txt = res.text()
// Access your resource here
Browser.console.log txt
return txt
}
//State
type MyInputString =
{Response : string}
// Message
type Message =
|ShowResponse
|Error
let getFromAPI =
getMe |> sprintf "%A"
//Update
let update msg model =
match msg with
|ShowResponse -> {Response = getFromAPI }
|Error -> {Response = "Errrrrr"}
//Helper function
let text(content:string) : ReactElement = unbox content
//Helper function
let init() = {Response = ""}
//View
let view model dispatch =
div
[]
[
div [] [ input[ Type "text"] ]
button [ OnClick (fun _ -> dispatch ShowResponse ) ] [ text "Show Me"]
div [] []
div [] [text (model.Response)]
]
Program.mkSimple init update view
|> Program.withReactSynchronous "werk"
|> Program.withConsoleTrace
|> Program.run ```
[1]: https://fable.io