1

How do I use types declared in my host project and served over Ajax in the generated FunScript code?

For example I lets say I declare a type T and then create a REST endpoint serving data in that format. Now if I want to load the data and use it from FunScript its no longer type T.


Edited with solution based on Alfanso's answer:

Assuming type "MyType" is defined in the base F# project and data matching this type served on localhost:6543/myData

let start () =
  async{  
    let url = "http://localhost:6543/myData"
    let req = System.Net.WebRequest.Create(url)
    let! data = req.AsyncGetJSON<MyType list>()
    Globals.window.alert( (sprintf "%A" data) )
  }
  |> Async.StartImmediate

What I was missing was

  • req.AsyncGetJSON
  • Use Async.StartImmediate
Andre
  • 4,560
  • 2
  • 21
  • 27
  • I blogged in more detail about how I got this working based on the answer below: http://andrevdm.blogspot.com/2014/11/f-funscript-with-nancyfx-and-ractive.html – Andre Nov 18 '14 at 11:06

1 Answers1

2

Could you please post some code to see better what you're exactly trying to do? For reference, you can see an example of how to exchange type-safe JSON values using FunScript.HTML extensions in this little project. In this case:

  • Types are shared between server, client and database using F# records with CLIMutable and System.Data.Linq.Mapping.Table attributes: Source
  • For the server, I'm using ASP.NET Web API which send types as JSON transparently: Source
  • In the client, I'm using the WebRequest.AsyncGetJSON<'T> extension from FunScript.HTML, which in the background just issue a XMLHttpRequest, parses the result with the browser JSON.parse method and uses unbox<'T> to "cast" the object to the desired type: here, here and here.

unbox<'T> is the little trick you'll often have to use if you want to use dynamic types in a statically-typed manner in F#.

I hope this helps!

  • That sounds like it may be the solution. I'll try that ASAP and update my question with code so that it is clearer. Thanks for the direction – Andre Nov 16 '14 at 13:41
  • Perfect thanks for the detailed answer and code sample! – Andre Nov 17 '14 at 13:47