Sending back an Observable from a rejected Promise

I am currently investigating whether I can convert a Promise rejection into a typed Observable.

Within my login component, I have a function that looks like this...

login() {
  const login$ = this.authenticationService.login(this.loginForm.value)
  login$
  .pipe(
    finalize(() => {
      this.loginForm.markAsPristine();
      this.isLoading = false;
    }),
    untilDestroyed(this)
  )
  .subscribe(
    (credentials) => {
      log.debug(`${credentials.username} successfully logged in`);
      this.router.navigate([this.route.snapshot.queryParams.redirect || '/'], { replaceUrl: true });
    },
    (error) => {
      log.debug(`Login error: ${error}`);
      this.error = error;
    }
  )
}

and the authentication service includes a method similar to this...

login(context: LoginContext): Observable<Credentials> {

  var data = {} as Credentials
  
  // Invoking a method that returns a Promise
  this.server.authenticate(LoginContext)
  .then((result) -> {
      data.username = result.user.username
      data.token = result.accessToken
      this.credentialsService.setCredentials(data, context.remember)
      // Uncertain about how to return data as an Observable here
      // return data
    })
  .catch((err) => {
      // Also unsure of how to handle errors and bubble them up for subscription
      // return throwError(err)
    })
}

Is it possible to return an Observable<Credentials> when the Promise resolves, and pass up the error if it rejects?

I understand that changing the authentication service function to return

Promise<Observable<Credentials>>
would solve the issue, but I am keen on exploring new solutions. Any insights on achieving this are greatly appreciated.

Answer №1

To easily convert a Promise to an Observable, utilize the from function:

import { from } from 'rxjs';

// ...

class MyClass {
  loginUser(context: LoginContext): Observable<Credentials> {
    return from(this.server.authenticate(LoginContext).then(result => {
      const credentials: Credentials = {
        username: result.user.username,
        token: result.accessToken
      }; 
      this.credentialsService.setCredentials(credentials, context.remember);
      return credentials;
    }));
  }
}

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

ensure that mocha does not consistently skip tests

When working with mocha, I include several unit tests that incorporate the skip it.skip('login (return photo)', function(done) { ... At times, I need to prevent skipping certain tests, such as right before a deployment. Is there a specific flag ...

Executing code asynchronously and handling callbacks using Process.nextTick and Promise

When I execute the following code: process.nextTick(() => console.log(8)) Promise.resolve("hi").then(t => console.log(t)) console.log(7); The output displayed is 7 8 hi This behavior is as expected because process.n ...

Incorporating input fields into an HTML form

I'm looking to enhance my form by adding input fields dynamically through the JavaScript function when I click on the add button: let i = 0; function increment() { i += 1; } function addFieldFunction() { let newDiv = document.createElement(&apos ...

Access the value of a specific field within an object using ng-options and use it to filter out other

I have created two separate lists. 1) The first list contains the service names. 2) The second list contains the product names assigned to each service name. Each product has a unique ID that matches it with its corresponding service. app.controller( ...

Changing the size of icons in an Alert using Material UI with React

Recently, Material UI unveiled the new 'Alert' component. Everything seems to be working well, except for the fact that I can't find a way to adjust the size of the icon. Here is my code snippet: <Snackbar open={true}> <Alert ...

"Discover the process of sending a JSON value from a PHP page to an HTML page using AJAX, and learn how to display the resulting data

I am currently validating an email ID using PHP and AJAX, with the intention of returning a value from the PHP page to the HTML in JSON format. My goal is to store this return value in a PHP variable for future use. All of this is being executed within C ...

How come my countdown application functions properly when accessed through the browser via the HTML page, but encounters issues when utilized with an HTTP server?

I have encountered an issue where the app functions correctly when I open the HTML file in my browser, but fails to load the CSS and JavaScript when accessing it through localhost:3000. HTML: <html> <head> <link href="./main.css" rel="st ...

"Step-by-step guide on setting up Angularjs ng-model in a Rails environment

Question regarding the utilization of two-way binding in AngularJS and Rails ERB files. Let's say the input value in my .erb file has an initial value like this: example.erb <input type="text" value=" <%= @item.title %> " ng-model ="item.t ...

Implement a sleek carousel within a Vue component

Hello, I am trying to add a single slick carousel component to a block that already contains 2 components in a template. However, when I do this, it distorts the images of the other component. <template v-if="isMobile"> <vue-slic ...

Exploring the intricacies of AJAX and jQuery: An example encountering a

After clicking the run button, an error appears in the Chrome console and there is no alert displayed. POST http://mysite/gd/add.php 503 (Service Unavailable) The issue seems to be with the index.php file: <html> <head> <script src ...

TypedScript: A comprehensive guide to safely omitting deep object paths

Hi there, I have a complex question that I would like some help with. I've created a recursive Omit type in TypeScript. It takes a type T and a tuple of strings (referred to as a 'path'), then removes the last item on the path and returns t ...

Could you please share the standard naming convention used for interfaces and classes in TypeScript?

Here's what I have: interface IUser { email: string password: string } class User { email: string password: string constructor(email: string, password: string) { this.email = email this.password = password } isEmailValid(): boo ...

Issue with HTTP interceptor failing to activate

I'm having trouble with my interceptor not triggering. Despite trying multiple solutions, I can't seem to get it working. The interceptor is failing to intercept http requests, resulting in the 'Authorization' header not being added. ...

The problem with URL encoding causing issues with Angular 2 navigation

I've encountered an issue with my Angular 2 website. When I input optional parameters in Chrome, such as this URL gets converted to and fails to locate the page in Chrome. Strangely, it works perfectly when pasted in incognito mode. As a newcomer to ...

The while-loop using Regex adds only a single value to my array

Within my variable htmlContent, there lies a string filled with properly formatted HTML code, which includes various img tags. The goal is to extract each value from the src attribute of these images and place them all in an array named srcList. The issu ...

Resetting form after submitting an image in Meteor

In my Meteor App, I am using CFS for uploading files and everything is working fine except for one issue. When I try to upload another image, the previous uploaded image remains in the form, so I need a way to clear the form after submitting the new image. ...

Retrieving the required Ng-checked checkbox (or radio button) in an ng-repeat loop within Angular framework

Looking for a way to validate a form that contains multiple radio checkboxes within an ng-repeat loop. How can I ensure the selected option is validated with the radio button input? Validation outside of the ng-repeat loop is functioning properly. For ex ...

Removing excess space at the bottom of a gauge chart using Echarts

After trying to implement a gauge chart using Baidu's Echarts, I noticed that the grid properties applied to other charts are working fine, but the bottom space is not being removed in the gauge chart. Even after applying radius(100%), the space at th ...

Troubleshooting the installation error for 'react-router-dom

I encountered an issue during the installation of react-router-dom. D:\react\routeingreact>npm i react-router-dom npm ERR! Cannot read property 'match' of undefined npm ERR! A complete log of this run can be found in: npm ERR! ...

How can the callback from C++ be successfully installed in the Javaobject window within QtWebkit?

I have successfully implemented HTML-JS to call a C++ method using QtWebkit. Now, I want to send a callback from the C++ method to the JavaScript window. How can I achieve this? Below is my code snippet. #include <QtGui/QApplication> #include <Q ...