Reputation: 61
Iam trying to get data from a web weather API, I'am getting the data by using WSClient.
Actually, I can println and visualize the data like this :
val futureResponse: Future[WSResponse] = complexRequest.get()
def weather = Action {
futureResponse.map {
response =>
println(response.json)
}
println(futureResponse)
Ok(views.html.weather("data"))
}
but I have trouble passing it to the view layer using Ok(views.html.weather("data"))
cause when i println(futureResponse)
its not json data it shows :
Future(Success(AhcWSResponse(StandaloneAhcWSResponse(200, OK))))
only println(response.json)
shows the valid data i want to send but its unreachable outside.
Upvotes: 0
Views: 183
Reputation: 1497
You need something on the lines of
def weather = Action.async {
complexRequest.get().map(response => Ok(views.html.weather(response.json)))
}
So basically, the json is only available when the future is completed, so you can only pass it to the view inside the map
function, also notice that I've used Action.async
this creates an action that expects a Future[WsResponse]
rather than just a WsResponse
Also bear in mind that the Futures
are memoised, so if you store the reference to it in a val
it will only execute once
EDIT: Fixed the future being stored in a val
to avoid problems with the memoisation
Upvotes: 2
Reputation: 192
It's unreachable because you will have to use a callback method to access/pass the content inside Future. That's the reason println(response.json)
inside map
callback shows the data/content you are interested.
You may refer to Accessing value returned by scala futures
Upvotes: 0