我很清楚如何在flex中使用HTTP服务,但我想在不同的ActionScript类中分离调用服务和获取服务响应的功能。那么有谁知道如何在flex中返回HTTP服务的响应?
例如
在UTILITY类我想要一个方法,我将给出一个URL,它将给我从该位置获得的数据。而已。请考虑以下代码段。参考代码取自could not be able to create http service programmitically in flex
private function callService():void
{
var requestObj:Object = {};
requestObj.q = cityName.text.toString();
requestObj.format = FORMAT;
requestObj.num_of_days = cNUMBER_OF_DAYS;
requestObj.key = API_KEY;
var weatherService:HTTPService = new HTTPService();
weatherService.url = BASE_URL;
weatherService.resultFormat = "object";
weatherService.showBusyCursor = true;
weatherService.request = requestObj;
weatherService.addEventListener(ResultEvent.RESULT , weatherService_resultHandler);
weatherService.addEventListener(FaultEvent.FAULT, weatherService_faultHandler);
weatherService.send();
}
protected function weatherService_resultHandler(event:ResultEvent):void
{
trace("got result");
**//WANT TO GIVE THIS RESULT BACK TO THE CALLER. SINCE RETURN TYPE OF
//METHOD IS VOID I CANNOT RETURN ANYTHING FROM HERE. HOW TO MAKE THIS
//METHOD TO RETURN DATA?**
}
protected function weatherService_faultHandler(event:FaultEvent):void
{
trace("got fault");
}
答案 0 :(得分:3)
根据项目的架构,有几种解决方案。主要思想是在服务接收响应时触发事件(或调用回调)并在调用者中处理它。示例中最简单的方法是在weatherService
方法中返回callService
对象,并在调用方(ResultEvent.RESULT
和FaultEvent.FAULT
)中添加相同的侦听器。这个解决方案的缺点是您必须在调用者中解析原始服务器响应,而不是使用一些已解析的值对象,但我注意到所有这些都取决于您的项目数据流。
UPD:回调使用的例子:
//map for storing the {service:callback} linkage
private var callbacks:Dictionary = new Dictionary(true);
/*
callback is a function like: function(success:Boolean, data:Object):void
*/
private function callService(callback:Function):void
{
var requestObj:Object = {};
requestObj.q = cityName.text.toString();
requestObj.format = FORMAT;
requestObj.num_of_days = cNUMBER_OF_DAYS;
requestObj.key = API_KEY;
var weatherService:HTTPService = new HTTPService();
weatherService.resultFormat = "object";
weatherService.showBusyCursor = true;
weatherService.request = requestObj;
weatherService.addEventListener(ResultEvent.RESULT, weatherService_handler);
weatherService.addEventListener(FaultEvent.FAULT, weatherService_handler);
var token:AsyncToken = weatherService.send();
var obj:Object = {callback:callback, service:weatherService};
callbacks[token.message.messageId] = obj;
}
protected function weatherService_handler(event:Event):void
{
var success:Boolean = event.type == ResultEvent.RESULT;
var token:AsyncToken = success ? ResultEvent(event).token : FaultEvent(event).token;
var obj:Object = callbacks[token.message.messageId]
var service:HTTPService = obj.service;
service.removeEventListener(ResultEvent.RESULT , weatherService_handler);
service.removeEventListener(FaultEvent.FAULT, weatherService_handler);
var data:Object = success ? ResultEvent(event).result : FaultEvent(event).fault;
var callback:Function = obj.callback;
delete callbacks[event.target];
callback(success, data);
}