Error overlooked in Typescript Angular

Is there a way to handle async code in a validation process where an action should only be performed if no exception is thrown? For example, the "CompletePlanConfirm()" method should only run if no exception occurs. The functions FirstCheck and SecondCheck return Observables. How can this be achieved?

completePlan() {
    try {
        this.validatePlan();
        this.completePlanConfirm();
    } catch (error) {
        throw error
    }
}

validatePlan() {
    this.planService.FirstCheck(this.plan.id).subscribe(
        data => {
            if (!data.result) {
                throw Error('Error 1')
            }
        });
    this.planService.SecondCheck(this.plan.id).subscribe(
        data => {
            if (!data.result) {
                throw Error('Error 2')
            }
        });
}

Answer №1

To achieve synchronous code execution, you can utilize async / await in your application.

Start by revising your validatePlan function to return an observable (along with modifications to prevent nested subscriptions):

validatePlan() {
  return this.planService.FirstCheck(this.plan.id).pipe(
    map(data => {
      if(!data.result) {
        throw Error('Error 1')
      }
    }),
    switchMap(() => this.planService.SecondCheck(this.plan.id))
  ).pipe(
     map(data => {
      if(!data.result) {
        throw Error('Error 1')
      }
    }),
  )
}

Subsequently, make completePlan an async function and insert the await keyword before calling the validatePlan function (ensure it is converted into a Promise using .toPromise()):

async completePlan() {

try {

  await this.validatePlan().toPromise();
  this.completePlanConfirm();
} catch (error) {
  throw error
}

By following these steps, the function execution will be synchronized and will pause at validatePlan until completion before proceeding further (thus avoiding attempting to confirm the plan if an error occurs).

Answer №2

To improve the clarity of your code, I suggest utilizing `async` and `await` in your plan checks to handle promises efficiently within your `completePlan` function.

async completePlan() {
    try {
        const response1 = await this.checkFirstPlan();
        const response2 = await this.checkSecondPlan();
        
        this.completePlanConfirm();
    } catch (error) {
        console.error(error);
        throw error;
    }
}

checkFirstPlan(): Promise<any> {
    return new Promise((resolve, reject) => {
        this.planService.FirstCheck(this.plan.id).subscribe((data: any) => {
            if (!data.result) {
                throw new Error('Error 1')
            }
            resolve(data);
        }, (error: any) => {
          throw new Error(msg);
        }, () => { });
      });    
}

checkSecondPlan(): Promise<any> {
    return new Promise((resolve, reject) => {
        this.planService.SecondCheck(this.plan.id).subscribe((data: any) => {
            if (!data.result) {
                throw new Error('Error 2')
            }
            resolve(data);
        }, (error: any) => {
          throw new Error(msg);
        }, () => { });
      });    
}

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

Utilize the gsap ScrollTrigger in conjunction with React's useRef() and Typescript, encountering issues with type mism

Recently, I've been trying to add some animation to a simple React Component using the GreenSock ScrollTrigger plugin. However, I ran into an issue due to types mismatch in my Typescript project. Here's a snippet of the code: import React, {useRe ...

Ways to fix a TypeScript syntax-checker error in Visual Studio

I am currently facing an issue while attempting to showcase an array using Angular and TypeScript. The error message that I encounter is quite perplexing and I am unsure of its meaning. Upon hovering my cursor over the Goal that is underlined in red, the ...

Steps to deactivating a styled button using React's styled-components:

I've created a very basic styled-components button as follows: import styled from 'styled-components'; const StyledButton = styled.button``; export const Button = () => { return <StyledButton>Default label</StyledButton> ...

Exploring Appsetting Configuration in AppModule of Angular 8

I'm looking to update my configuration in the appsettings file by replacing a hardcoded string with a reference to the appsetting. Currently, I have this hardcoded value in appmodule.ts: AgmCoreModule.forRoot({ apiKey: 'testtesttest', li ...

Tips for creating a flexible popover widget

I am facing an issue with my project that has a popover (ng-bootstrap) similar to what I need. The problem is that the tooltips and popovers are not flexible when it comes to resizing the page. To address this, I attempted to put a mat-grid (which works pe ...

Troubleshooting: Angular 2 router events subscription not triggering

Currently, I am utilizing a breadcrumbs component that subscribes to the router events. However, there is an issue where the subscription does not trigger the first time the component loads. ngOnInit(): void { console.log("oninit beradcumbs"); this.ro ...

Exceed the capacity of a React component

Imagine having a React component that can render either a <button>, an <a>, or a React Router <Link> based on different props passed to it. Is it possible to overload this component in order to accept the correct props for each scenario? ...

Material-UI: Tips for aligning pagination button in the center

My attempt to implement Pagination using Material-UI went well, but now I am struggling to center the arrow buttons and page numbers. I initially tried centering them by wrapping them in a <div style={{textAlign: "center"}}>, however this ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

Tips for utilizing method overload in TypeScript with a basic object?

Looking at this code snippet: type Foo = { func(a: string): void; func(b: number, a: string): void; } const f: Foo = { func(b, a) { // ??? } } An error is encountered stating: Type '(b: number, a: string) => void' is not assign ...

Improprove performance in Angular by efficiently updating the view through the service

Utilizing the uiSettings service, I am able to control different parts of templates based on user data. Currently, I am directly accessing this service from the template like so: <li *ngIf="uiService.demoButton()"> <button [router ...

Exploring Angular 2: Offering distinct dependencies to children within a shared component

After going through the Angular documentation, I learned that a child component can request a dependency using an abstract class, and the parent can supply a concrete class to fulfill the child's dependency. For instance: @Component({ ... p ...

Ensure that the child component form is validated upon clicking a button in the parent component in Angular

I have set up a parent template with two buttons. One button serves as the Submit option for the parent/child form, while the other should specifically validate the child component form. When I click the Submit button, it successfully validates both forms ...

Tips for crafting a test scenario for input alterations within Angular

Hello there, currently I am working on an application using Angular and TypeScript. Here is a snippet of my template code: <input type="text" placeholder="Search Results" (input)="searchInput($event)"> And here is the TypeScript code for the searc ...

Steps for automatically incrementing a number when adding an item to an array using Angular

I am currently working on adding values to an array and displaying them in the view. Everything is functioning correctly, but I would like to include an auto-incrementing number with each item. The initial array is stored in a data.json file. [ {"i ...

What methods are available to pass a variable value between two components in Angular 2?

I've been experimenting with Angular2 and recently created a component called appmenu using angular cli. The code in appmenu.html looks like this: <ul> <li (click)="menuitem1()">Menu Item 1</li> <li>Menu Item 2</li> ...

Ensure that the string functions as the primary interface

I'm working with an interface that looks like this interface Cat { color: string, weight: number, cute: Boolean, // even though all cats are cute! } Currently, I need to accomplish something similar to this const kitten: Cat = ... Object. ...

Achieving CommonJS imports compilation with Typescript

In my TS file, I've included a 3rd party package using import XXX { YYY, ABC, 123 } from 'XXX'; While it compiles to CommonJS without any issues, I'd prefer to have it compiled to an ESModule instead. I tried changing the target and mo ...

What is the best way to employ the *ngIf directive in order to alter an image?

I'm in the process of developing an application using the following technologies. How can I implement the use of *ngIf directive to switch between two images? Here's a more detailed explanation: I have two images, one representing the male symbol ...

"Encountering issues with getStaticPaths not generating any paths

I have a folder named data which contains a file called events.ts: export const EventsData: Event[] = [ { name: 'School-Uniform-Distribution', images: ['/community/conferences/react-foo.png', "/community/conferences/react ...