Convert parameterized lambdas for success and failure into an observable using RxJS

There is a function exported by a library that I am currently using:

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

At the moment, my usage of this function looks like this:

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);

My query is whether it's possible to wrap this call using rxjs. I believe it can be done, but I'm not sure how to go about it... Any thoughts?

Answer №1

To encapsulate the callbacks, you can utilize Rx.Observable.create in the following manner:

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

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

readContent('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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...

What is the best way to group an array based on a dynamic key?

My goal is to group values in an array by a given ID. I've attempted a method for this, but it's not working for dynamic keys. Here is the current array: let employees = [{"employeeDetail": [{"empID": "XXYYZZ11"," ...

Using the <head> or <script> tag within my custom AngularJS2 component in ng2

When I first initiate index.html in AngularJS2, the structure looks something like this: <!doctype html> <html> <head> <title>demo</title> <meta name="viewport" content="width=device-width, initial-scal ...

TypeScript: empty JSON response

I am encountering an issue with the JSON data being blank in the code below. The class is defined as follows: export class Account { public amount: string; public name: string; constructor(amount: string, name: string) { this.amount = amount; t ...

What is the best way to display a loading screen while simultaneously making calls to multiple APIs?

I'm currently working with Angular 8 to develop an application that retrieves responses from various APIs for users. The application is designed to simultaneously call multiple APIs and I require a loading indicator that stops once each API delivers a ...

Why am I having trouble iterating through my array object?

Trying to showcase the contents of object within an array. However, unable to showcase any results. Why is this happening? This is what I've attempted so far: Demo available here: https://stackblitz.com/edit/ionic-dsdjvp?file=pages%2Fhome%2Fhome.ts ...

What is the best way to create a custom hook that updates in response to changes in state?

My situation involves a custom hook that handles a specific state variable. After making changes to the state, it doesn't update right away. To solve this issue, I need to subscribe to it using useEffect. The challenge is that I can't directly ...

Associative TypeScript Arrays

I'm attempting to organize reservations based on business ID in order to achieve a specific end result. Here is the desired output: [ [businessID1] => [Object1,Object2, Object3], [businessID2] => [Object1,Object2], [businessID3] => [Object1,Objec ...

Ways to resolve the issue of npm being unable to globally install typescript

While trying to globally install TypeScript using npm sudo npm install -g typescript An error occurs during the installation process with the following message: ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/typescript/bin/ ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

Get the download URL from Firebase Storage and save it into an array within Firestore

I am currently working on a project to upload multiple image files to Firebase Storage and then store their download URLs in a single array within Firestore. uploadImages(name, images) { for (let i = 0; i < images.length; i++) { const file = ...

Can you explain the distinction between needing ts-node and ts-node/register?

Currently, I am conducting end-to-end tests for an Angular application using Protractor and TypeScript. As I was setting up the environment, I came across the requirement to include: require("ts-node/register") Given my limited experience with Node.js, I ...

Issue with triggering (keyup.enter) in Angular 8 for readonly HTML input elements

My goal is to execute a function when the user presses Enter. By setting this input as readonly, my intention is to prevent the user from changing the value once it has been entered. The value will be populated from a popup triggered by the click attribut ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

`How to Merge Angular Route Parameters?`

In the Angular Material Docs application, path parameters are combined in the following manner: // Combine params from all of the path into a single object. this.params = combineLatest( this._route.pathFromRoot.map(route => route.params) ...

Modifying the date format of the ag-Grid date filter

On my Angular 5.2.11 application, I utilize ag-grid to showcase a table. The date column is configured with the default date filter agDateColumnFilter as per the documentation. After enabling browserDatePicker: true, the Datepicker displays dates in the ...

Testing abstract class methods in Jest can ensure full coverage

In my project, I have an abstract generic service class. export default abstract class GenericService<Type> implements CrudService<Type> { private readonly modifiedUrl: URL; public constructor(url: string) { this.modifiedUrl = ...

This element is not suitable for use as a JSX component since its return type 'void' is not a valid JSX element. Please check the return type to ensure it is compatible with

I have been working on this code snippet: function searchData(searchWord: any) { if (originalData.length > 0) { if (searchWord !== "") { setDataList([...originalData.filter((svc: any) => ...

Using ngFor results in duplicate instances of ng-template

I'm facing a challenge with the ngFor directive and I'm struggling to find a solution: <ng-container *ngIf="user.images.length > 0"> <div *ngFor="let image of images"> <img *ngIf="i ...

Tips for avoiding the <p> and <br> elements while using a ContentEditable div

Upon pressing the enter key, the editor automatically inserts paragraph and page break elements. What are some strategies to avoid these unwanted elements in the editor? ...