Handling errors in nested Promises and rxjs Observables in Angular 12 with Typescript and rxjs

My current code involves a mix of nested Promises and subscriptions, but all I want to do is this:

  • Call my function bar() and determine if it executed successfully or encountered an error

Current approach: Currently, my bar() function returns a boolean Observable. I handle errors separately for Promises using .catch and for rxjs Observables with the error handler:

    foo(): void {
       this.bar.subscribe((data: boolean) => console.log('the function call bar() was ' + data));
    }

    bar(): Observable<boolean> {
    let subject = new Subject<boolean>();
    
        this.httpHandler.newFoo().subscribe(
        (data) => 
          this.checkBar(data)
            .then((barData) => 
              this.httpHandler.updateBar().subscribe(
                (barData2) => subject.next(true),
                (error) => subject.next(false)))
            .catch(err => subject.next(false)),
        (error) => subject.next(false));

        return subject.asObservable();
    }

This setup may seem convoluted and excessive for simply determining if the bar() function execution went smoothly. Is there a cleaner way to manage nested errors in this scenario?

Thank you for your help

Answer №1

Here is a concise way to write the code:

this.httpHandler.newFoo().pipe(
  switchMap(data =>
    from(this.bar(data)).pipe(
      switchMap(() =>
        this.httpHandler.updateBar().pipe(
          mapTo(true)
        )
      )
    )
  ),
  catchError(() => of(false))
)

To convert a promise into an observable, use from(). Utilize switchMap() to move between observables. Then simply chain your function calls like this:

this.httpHandler.newFoo() -> this.bar() -> this.httpHandler.updateBar()

Finally, return true at the end, or false if there is any error.

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

Each element in ngFor triggers the invocation of ngAfterContentInit by Angular

In my Angular 11 (Ionic 5) app, I have a scenario with two components: A ContainerComponent and a BoxComponent. Both of these components are completely transparent (template: '<ng-content></ng-content>'). The challenge is for the cont ...

Typescript struggling to comprehend the conditional rendering flow

I am facing an issue with the code snippet below: import * as React from 'react' type ComponentConfig = [true, {name: string}] | [false, null] const useComponent = (check: boolean): ComponentConfig => { if (check) { return [true, {name ...

Cease monitoring for operations within NGRX

One challenge I am facing is related to common components that dispatch actions. Take "Status Selection" for example, a component used in various modules of my application. In each module, there are effects triggered by this action. However, the issue ari ...

Using TypeScript's union type to address compatibility issues

Below is a small example I've created to illustrate my problem: interface testType { id: number } let t: testType[] = [{ id: 1 }] t = t.map(item => ({ ...item, id: '123' })) Imagine that the testType interface is source ...

Improving the performance of angular-map when adding numerous markers

I am currently working on a map project in Angular 7 that involves displaying 1600 markers, but I'm encountering slow loading times. Within my .ts file, I have a function that retrieves latitude and longitude values from a JSON file: private _popula ...

What is the process of converting a union type into a union of arrays in TypeScript?

I have a Foo type that consists of multiple types For example: type Foo = string | number I need to receive this type and convert it into an array of the individual types within the union type TransformedFoo = ToUnionOfArray<Foo> // => string[] ...

Developing a custom pipe in Angular4

Can anyone explain why the code snippet below has (limit) in parentheses? import { Pipe, PipeTransform } from '@angular/core' @Pipe ({ name: 'summary' }) export class SummaryPipe implements PipeTransofm { transform(value: string, l ...

TypeScript: a sequence of symbols representing a particular <type>

Perhaps I'm going crazy. I have a roster of potential nucleotides and a corresponding type: const DNA = ['G', 'C', 'T', 'A'] as const; type DNA = typeof DNA[number]; So, a DNA strand could be a sequence of an ...

Navigate through Angular 2 array elements

I am facing an issue where I have an array and I need to display only a single object from the array at a time. The goal is to cycle through the array using a button, but I'm struggling to figure out how to display just one object at a time. You can s ...

Find the combination of all potential function outputs

I'm trying to figure out why the compiler doesn't infer A as a union type like string[] | number[] when it fails. Instead, A is inferred as the first return value, which in this case is string[]. Is there a solution to this issue? const define = ...

The MUI theme seems to be missing its application

As a newcomer to MUI, I'm facing challenges when trying to apply a custom theme. My goal was to create a new variant for the button using the code snippet below: // @ts-nocheck import React, {FC} from 'react'; import { createTheme, ThemeProv ...

Tips for including an onclick event for a single input radio button in Angular 5

I am working with Angular 5 and have created 4 components. In the first component, there are 3 radio buttons that should navigate to other components when clicked. However, the radio button does not get checked. How can I make sure that the radio button is ...

Exploring the concepts of relative and absolute paths in JavaScript

I'm struggling to grasp the concept of relative and absolute paths. Can someone please help explain how they operate in relation to the directory? I have the following code but I am unable to include the PostService module. import { Component } from ...

How can I access members outside of a class without a name in Typescript?

I recently developed an "anonymous" class inspired by this insightful discussion on Typescript anonymous classes. However, I'm facing a challenge in accessing the outer scope members. Here's a snippet of my code for context: class BaseCounter { ...

The specified Observable<Response> argument cannot be assigned to the parameter of type Observable<Response> at hand

Confused... React, Gulp private performAction(inputValue: Observable<Response>) { ... } ... triggerAction() { performAction(this.http.get(...)) } ...

What purpose does the pipe method serve in RxJS?

It seems like I understand the basic concept, but there are a few unclear aspects. Here is my typical usage pattern with an Observable: observable.subscribe(x => { }) If I need to filter data, I can achieve this by: import { first, last, map, reduce, ...

Tips for utilizing the "this" keyword in TypeScript

As a newcomer to TypeScript, I am seeking assistance on how to access the login service within the authenticate function. Despite using the 'this' keyword to retrieve the login service, it seems ineffective. Additionally, I find myself puzzled by ...

Issue with displaying Angular chart only resolves after resizing window following routing updates

Hey there! I'm having trouble getting my chart to show up after adding routing to my 3 tabs. Previously, without routing, everything worked fine. Now, the graph only appears after resizing the window. The chart is using PrimeNG chart with the Chart.js ...

Verify the user's identity without relying on Angularfire

I am currently developing an application that requires user authentication. I have decided to use firebase for the database and have implemented node.js to retrieve data from it. Now, my next step is to create a login page where users can authenticate us ...

Designing a personalized mat-icon using the Github SVG

Trying to create a unique custom SVG mat-icon by loading the SVG directly from Github. My initial attempt using DomSanitizer was documented in this article, and it successfully loaded the SVG via HttpClient. Now, I am attempting to achieve this directly t ...