Converting a Promise to an Observable in Angular using Typescript

I have a working method that functions as intended:

getdata(): Promise<any> {
    let query = `SELECT * FROM table`;
    return new Promise((resolve, reject) => {
      this.db.query(query, (error, rows) => {
        if(error) reject(error);
        resolve(rows);
      });
    });
}

ngOnInit() {
    this.myservice.getdata().then(result => {
      this.data = result;
    })
}

I'm currently using Angular 9 along with Electron.

Is there a way I can modify this to operate as an Observable instead?

Answer №1

By simply wrapping any promise with from, you can easily convert it into an observable:

fetchData(): Observable<any> {
    let query = `SELECT * FROM table`;
    return from(new Promise((resolve, reject) => {
      this.db.query(query, (error, rows) => {
        if(error) reject(error);
        resolve(rows);
      });
    }));
}

Alternatively, you have the option to bypass the promise and directly create an observable:

fetchData(): Observable<any> {
    let query = `SELECT * FROM table`;
    return new Observable((obs) => {
      this.db.query(query, (error, rows) => {
        if (error) {
          obs.error(error);
        } else {
          obs.next(rows);
          obs.complete();
        }
      });
    });
}

Answer №2

One potential solution is to utilize a RxJS Subject observable.

completed$ = new Subject<any>();

retrieveData(): Observable<any> {
  const result = new BehaviorSubject<any>(null);
  const query = `SELECT * FROM table`;
  this.db.query(query, (error, rows) => {
    error ? result.error(error) : result.next(rows);
  });
  return result.asObservable();
}

ngOnInit() {
  this.myservice.retrieveData().pipe(
    takeUntil(this.completed$)
  ).subscribe(
    rows => {
      if (rows) {          // <-- validate response
        this.data = rows;
      } 
    },
    error => { }
  );
}

ngOnDestroy() {
  this.completed$.next();
  this.completed$.complete();
}

Answer №3

To transform a function containing a callback where the first parameter is error (referred to as "Node.js-style callback") into an Observable, it is recommended to use bindNodeCallback:

retrieveData(): Observable<any> {
  const query = `SELECT * FROM table`;
  return bindNodeCallback(this.db.query)(query)
}

// handling subscription:
ngOnInit() {
  this.dataService.retrieveData().subscribe(response => {
    this.data = response;
  });
}

Source

Answer №4

A recommended approach is to utilize the bindNodeCallback method.

fetchData(): Promise<any> {
  return bindNodeCallback(this.database.query)(`SELECT * FROM table`);
}

initialize() {
  this.myService.fetchData().subscribe(response => {
    this.data = response;
  });
}

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

The Challenge of Iterating Through an Array of Objects in Angular Components using TypeScript

Could someone please explain why I am unable to iterate through this array? Initially, everything seems to be working fine in the ngOnInit. I have an array that is successfully displayed in the template. However, when checking in ngAfterViewInit, the conso ...

After the upgrade from Angular 5.2 to Angular 6, Bootstrap 4 dropdown and Bootstrap-select dropdown seem to have lost their dropdown functionality. This issue arose after updating to Bootstrap 4 and jquery

Update: Upon further investigation, I experimented with a standard Bootstrap 4 dropdown and encountered the same issue – it would not open. This leads me to believe that the problem may not be specific to the selectpicker class or the bootstrap-select de ...

Tips for arranging mat-option in alphabetical order using typescript in Angular 7 Material Design

According to the Angular documentation, there is currently no orderBy pipe available for sorting. It is recommended to implement the sort functionality in the component. However, as a beginner in Angular, I am unsure of how to do this. Can anyone provide a ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

Warning: NG2 RC5 has deprecated the use of HTTP_PROVIDERS

With the release of Angular2 version RC5, there have been some changes such as deprecating HTTP_PROVIDERS and introducing HttpModule. While my application code is functioning properly with this change, I am facing difficulties in updating my Jasmine tests. ...

What is the syntax for invoking a function within a nested function in TypeScript?

Is there a way to call the function func2 from within the sample function of function func1? Any suggestions on how to achieve that? class A { public func1() { let sample = function() { //call func2... but ...

The application within the Main Module is not being acknowledged by the other components within the module

I am facing an issue with my AngularJS application where the directive I created within the 'FormTest' module is not recognizing the variable 'app' even though it is defined within the same module. The error message I receive is TS2304 ...

In Angular 2, transferring data from a parent route to a child route

I have set up a route named "home" with three child routes: documents, mail, and trash. Within the home route component, there is a variable called 'user'. While I am familiar with various methods of passing information between parent and child c ...

Building secure authentication with Angular, node.js, and an identity provider through SAML integration

Implementing SSO using SAML2 is my goal, but I am facing a challenge with a distributed system where each instance operates independently on its server. There are three instances in the environment: Instance #1: an angular frontend Instance #2: a node.js ...

Unable to process JSON request in Node.js

I have the following data in Angular that I need to pass to a Node API. The data includes a JSON object that is being sent to the Node API using the POST method. var myData = { "que": { "id": 1, "status": 1, "option": [ ...

Guide on implementing a .catch method in Firebase's onSnapshot function

I have recently developed an Ionic Firebase chat application. I seem to be encountering an issue with setting up a query snapshot when initializing the message page. Here is the code snippet that I am using: ngOnInit() { this.messageService.getA ...

The attribute 'limitTags' is not present in the type 'IntrinsicAttributes & AutocompleteProps'

The Versions of Material UI and Lab I am Utilizing "@material-ui/core": "^4.8.3", "@material-ui/lab": "^4.0.0-alpha.44", Visit the component here Snippet of My Code <Autocomplete multiple limitTags={2} id="multiple-limit-tags" ...

Ways to display a component using *ngIf else

As a beginner in angular, I decided to create a simple app to help me learn the basics. The concept of my app involves two players entering their names in separate input fields. Once they click a button, the game begins and displays their names along with ...

"Can anyone provide guidance on how to customize form fields in Angular Material 16, such as removing borders, changing colors, and other

After upgrading my angular material to version 16, all the UI elements I had in place became distorted due to the introduction of mdc. The CSS code I was using before to customize elements like this: ::ng-deep .mat-form-field-appearance-outline .mat-form- ...

Tips for arranging backend data horizontally within Bootstrap horizontal cards

After setting up my Angular application, I created a dashboard page and made API calls for dynamic signals (signal-1, signal-2, etc). To showcase this data, I decided to use Bootstrap horizontal cards. However, I'm facing an issue with displaying the ...

Steps for developing a Global service in Angular

I've come across many discussions on global angular services, but none seem to truly embody the concept of "global". I'm curious if it's feasible to develop a service that doesn't require importing everywhere it's used (i.e. truly ...

Guide to altering the characteristics of a button

Here is the code for a button within My Template: <div *ngFor="let detail of details" class = "col-sm-12"> <div class="pic col-sm-1"> <img height="60" width="60" [src]='detail.image'> </div> <div ...

Encountering a Spring Boot 404 error when deploying static content as a jar file

Utilizing a Spring Boot application alongside an Angular JS project housed in separate modules raises some concerns. The Angular JS files, located within the 'dist' folder, have been converted into jar files and integrated into the Spring Boot se ...

What steps should be taken to rectify the issue in the Angular HttpClient concerning the delete method?

(English is not my first language so please forgive me) Hello, I am new to Angular and I am attempting to make an HTTP request that deletes a doctor when a button is clicked. However, I am struggling with what steps I need to take to get my code working pr ...

Iterating over an object and inserting values into a JavaScript object using the ascending count as the identifier

Illustration: { Are you a coffee drinker?: yes, Do you like to exercise regularly?: no, How often do you eat out at restaurants?: 3 times a week, What is your favorite type of cuisine?: Italian } Results: {yes: 1, no: 1, 3 time ...