Friday, September 7, 2007

Working With Data in Flex : Using HTTPService

<mx:Model> tag allows you to build a client-side data-model. AS can access it in id.tagName format. When using databinding in MXML, it is indicated by {}. You can either type the tags or specify an external file. Useful to embed data that will not change (like options in option box/label text). Also useful for applications that need data offline. However this data is not typed: can result in poor performance and severly limit error trapping. It is just a simple substitute for server-side data. Can be addressed by using AS class for client side data-structure. Another reason that it is a bad idea is because it embeds XML into the swf. Besides increasing the size it also means that we need to recompile the swf every time we change the XML. A better option will be to pick the XML at runtime using the HTTPService class. It will retrieve XML using HTTP/HTTPS protocol by making a GET or POST request.

HTTPService class can be used to make asychronous calls. send() method of the object is used to send the request. After data has been received, result event (ResultEvent) is broadcast. The result is stored in lastResult property. A resultFormat can be specified or Flex will parse it approproately. Format can be array, e4x, flashvars, object, text or xml.

Flex gives the flexibility to convert to native XML object (E4X) or to directly convert into a object(like ArrayCollection, XMLListCollection).

For automatic conversion, we will have a tag similar to this in the MXML:
<mx:HTTPService id="serviceId" url="http://www.myUrl.com/myXml.xml" result="handlingFunc(event)" fault="handleFault(event)"/>

Use fault event to handle errors. The event in this case will be FaultEvent and not ResultEvent

Questions:
  1. What are the advantages and disadvantages of using a Model tag in flex?
  2. How can you avoid using a Model tag?
  3. Describe in brief how HTTPService class works.
  4. What are possible result formats for HTTPService?
  5. What are the advantages of using HTTPService?
Sample MXML would make sense after a few more writings in this series. This is a very important feature in flex and well worth the time spent on it :) !

2 comments:

Unknown said...

Do you know why an http service would return the same result after the initial .send(); was sent.
Its returns the same result even though the .php file returns new data upon execution.

Saveen said...

I am not sure Nathan. Will have a look and get back if I get an answer