rxjs:将成功/失败参数化lambdas包装成一个observable

时间:2017-12-19 14:59:27

标签: typescript rxjs

我正在使用导出此功能的库:

export function read(
    urlOrRequest: any,
    success?: (data: any, response: any) => void,
    error?: (error: Object) => void,
    handler?: Handler,
    httpClient?: Object,
    metadata?: Object): any;

目前,我正在使用它:

var request =
{
    headers: oHeaders,
    requestUri: "http://odatasampleservices.azurewebsites.net/V4/OData/OData.svc/Products",
    data: null,
};

var successFunction = function(data)
{
    document.getElementById("simpleReadWithMetadata").innerHTML = JSON.stringify(data, undefined, 2);
};

var failFunction = function(err)
{
    alert(JSON.stringify(err));
};

oData.read(request, successFunction, failFunction, null, null, metadata);

所以,我的问题是,我可以使用rxjs包装此调用吗?我想这是可能的,但我不知道如何得到它...任何想法?

1 个答案:

答案 0 :(得分:2)

您可以使用Rx.Observable.create来包装回调,如下所示:

function mockRead(urlOrRequest, success, error, handler, httpClient, metadata) {
  if (urlOrRequest === 'success') {
    success('data', 'response');
  } else {
    error('oops...');
  }
}

function read(urlOrRequest, success, error, handler, httpClient, metadata)
{
  return Rx.Observable.create(o => {
    mockRead(
      urlOrRequest,
    	(data, response) => {
      	o.next({ data, response });
      	o.complete();
    	},
      (error) => {
      	o.error(error);
    	},
      handler,
      httpClient,
      metadata
    );
  });
}

read('success')
  .subscribe(
  	x => { console.log('next', x); },
  	x => { console.log('error', x); },
  	() => { console.log('complete'); }
  );
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>