如何将 Future 数据传递给视图?
How to pass a Future data to the view?
我正在尝试从网络天气中获取数据 API,我正在使用 WSClient 获取数据。
实际上,我可以像这样打印和可视化数据:
val futureResponse: Future[WSResponse] = complexRequest.get()
def weather = Action {
futureResponse.map {
response =>
println(response.json)
}
println(futureResponse)
Ok(views.html.weather("data"))
}
但我无法使用 Ok(views.html.weather("data"))
将其传递到视图层,因为当我 println(futureResponse)
它显示的不是 json 数据时:
Future(Success(AhcWSResponse(StandaloneAhcWSResponse(200, OK))))
只有 println(response.json)
显示了我想发送的有效数据,但在外部无法访问。
无法访问,因为您必须使用回调方法 access/pass Future 中的内容。这就是 println(response.json)
在 map
回调中显示您感兴趣的 data/content 的原因。
您可以参考Accessing value returned by scala futures
您需要符合
的内容
def weather = Action.async {
complexRequest.get().map(response => Ok(views.html.weather(response.json)))
}
所以基本上,json 只有在 future 完成时才可用,所以你只能将它传递给 map
函数内的视图,还要注意我使用了 Action.async
这会创建一个需要 Future[WsResponse]
而不仅仅是 WsResponse
的动作
还要记住 Futures
是记忆的,所以如果你将对它的引用存储在 val
中,它只会执行一次
编辑:修复了存储在 val
中的未来以避免记忆问题
我正在尝试从网络天气中获取数据 API,我正在使用 WSClient 获取数据。
实际上,我可以像这样打印和可视化数据:
val futureResponse: Future[WSResponse] = complexRequest.get()
def weather = Action {
futureResponse.map {
response =>
println(response.json)
}
println(futureResponse)
Ok(views.html.weather("data"))
}
但我无法使用 Ok(views.html.weather("data"))
将其传递到视图层,因为当我 println(futureResponse)
它显示的不是 json 数据时:
Future(Success(AhcWSResponse(StandaloneAhcWSResponse(200, OK))))
只有 println(response.json)
显示了我想发送的有效数据,但在外部无法访问。
无法访问,因为您必须使用回调方法 access/pass Future 中的内容。这就是 println(response.json)
在 map
回调中显示您感兴趣的 data/content 的原因。
您可以参考Accessing value returned by scala futures
您需要符合
的内容def weather = Action.async {
complexRequest.get().map(response => Ok(views.html.weather(response.json)))
}
所以基本上,json 只有在 future 完成时才可用,所以你只能将它传递给 map
函数内的视图,还要注意我使用了 Action.async
这会创建一个需要 Future[WsResponse]
而不仅仅是 WsResponse
还要记住 Futures
是记忆的,所以如果你将对它的引用存储在 val
中,它只会执行一次
编辑:修复了存储在 val
中的未来以避免记忆问题