我有一个使用SOAP Web服务的Angular 2服务。为此,我使用具有回调函数的Javascript SOAP客户端。我知道服务方法的结果可能是Observable
或Promise
,但我不知道如何从回调函数返回服务。
这是我目前的代码:
import { Injectable } from '@angular/core';
declare var SOAPClient: any;//<-- The library I'm using, it doesn't have types
@Injectable()
export class SoapService {
connection_url: Map<string,string>;
constructor() {
this.connection_url = new Map<string, string>();
this.connection_url.set('Example', 'http://localhost:8080/MYAPP_EJB/ExampleSvc');
}
consume(service_name: string, method: string, parameters?: Map<string,any>){
var that = this;
return new Promise<any>(function(resolve){
var params = new SOAPClientParameters();
if(parameters !== null){
for (let parameter of parameters.keys()){
params.add(parameter,parameters.get(parameter));
}
}
//Below is the line where I use the function with the callback function argument (function(j)), where j represents the response from the Web Service
SOAPClient.invoke(that.connection_url.get(service_name), method,params,true,
function(j){
return new Promise<any>(function(resolve){
console.log('Web Service Answer: ' + j.answer.entry.value);
return j;
});
}); //End of SOAPClient.invoke()
}); //End of promise of consume()
}//End of consume()
}//End of class
我可以做些什么来使用consume()为组件提供Web服务响应?我是否需要对SOAPClient进行一些修改?
谢谢。
我使用了Robin的答案并使用了bindCallback
(与fromCallback
相同的想法,请参阅bindCallback以供参考),使用SOAPClient.invoke
作为该函数的参数。结果函数与原始函数相同,但不需要回调函数,而是返回Observable
,我可以订阅,然后解析consume()
的承诺。
新代码:
import { Injectable } from '@angular/core';
import * as Rx from "rxjs";
declare var SOAPClient: any;//<-- The library I'm using, it doesn't have types
@Injectable()
export class SoapService {
connection_url: Map<string,string>;
invokeSoapClient: any;
constructor() {
this.connection_url = new Map<string, string>();
this.connection_url.set('Example', 'http://localhost:8080/MYAPP_EJB/ExampleSvc');
this.invokeSoapClient = <any> Rx.Observable.bindCallback(SOAPClient.invoke);
}
consume(service_name: string, method: string, parameters?: Map<string,any>){
var that = this;
return new Promise<any>(function(resolve){
var params = new SOAPClientParameters();
if(parameters !== null){
for (let parameter of parameters.keys()){
params.add(parameter,parameters.get(parameter));
}
}
var invokeObs = that.invokeSoapClient(that.conexion_url.get(service_name), method, params, true);
invokeObs.subscribe(r => {resolve(r[0])}); //r is the answer from SOAPClient invoke, I just needed the response part.
}); //End of promise of consume()
}//End of consume()
}//End of class