Angular - Showing validation messages post successful execution of two functions

I have encountered an issue with my form submission process involving two functions. When both functions succeed, I want to display a successful validation message. However, currently the success message is displayed even if the second function fails. How can I ensure that both functions are successful before showing the validation message?

First Function

registerUser(user: cusInfo) {
    let userinfo = { cusInfo: { ...user } }
    this.registrationService.saveUserInfo(userinfo).subscribe(data => {
        // handle success
        },
        error => {
        // handle error
        });
}

Second function

registerInfo({ code,name }) {
    let item = { "reserve": { code,name} };
    console.log(item);
    this.registrationService.infoRequest(item).subscribe(data => {
        // handle success
        },
        error => {     
        // handle error
        });
}

Form submit

registerCustomer(item, info, reservelockerform: NgForm) {
    this.alertService.clear();
    this.registrationService.checkDuplicateUser(info.userName).subscribe(data => {
        if (data.executionDescription == 'Success') {
            this.registerUser(info); // call first function
            this.registerInfo(item); // call second function
            this.alertService.success('Registration has been made successfully');
        } else {
            this.alertService.error(data.executionDescription);
        }
    });

}

In order to solve the issue of displaying the validation message correctly, I need to modify my form submit function to only show it when both functions have succeeded.

Answer №1

Imagine you are sending requests and waiting for the responses back while checking the status of both responses at the same time, you might want to consider using forkJoin.

Ensure that both the registerUser and registerInfo methods are updated to return an Observable.

registerUser(user: any) {
  let userinfo = { cusInfo: { ...user } };
  return this.registrationService.saveUserInfo(userinfo);
}

registerInfo({ code, name }) {
  let item = { reserve: { code, name } };
  console.log(item);
  return this.registrationService.infoRequest(item);
}

registerCustomer(item, info, reservelockerform: NgForm) {
  this.alertService.clear();
  this.registrationService
    .checkDuplicateUser(info.userName)
    .subscribe((data) => {
      if (data.executionDescription == 'Success') {
        forkJoin([this.registerUser(info), this.registerInfo(item)])
          .subscribe({
            next: (data: any) => {
              if (
                data &&
                data[0] &&
                data[0].status == 'success' &&
                data[1] &&
                data[1].status == 'success'
              )
                this.alertService.success(
                  'Registration has been successfully completed'
                );
              else this.alertService.error('Registration has failed');
            },
            error: (err) => {
              console.log(err);
              this.alertService.error('Registration has failed');
            },
          });
      } else {
        this.alertService.error(data.executionDescription);
      }
    });
}

Explore Sample StackBlitz Demo

Answer №2

Here's a simple solution:

Execute the functions in a specific order as shown below:

First Function :

registerUser(user: cusInfo, item) {
let userinfo = { cusInfo: { ...user } }
this.registrationService.saveUserInfo(userinfo).subscribe(data => {
    this.registerInfo(item);
  }, error => { });
}

Second function :

registerInfo({ code,name }) {
let item = { "reserve": { code,name} };
this.registrationService.infoRequest(item).subscribe(data => {
   this.alertService.success('Registration has been made successfully');
  }, error => {  });
}

Form submit :

registerCustomer(item, info, reservelockerform: NgForm) {
this.alertService.clear();
this.registrationService.checkDuplicateUser(info.userName).subscribe(data => {
    if (data.executionDescription == 'Success') {
        this.registerUser(info, item);
    } else {
        this.alertService.error(data.executionDescription);
    }
});

}

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

When working with Laravel and submitting a form using the `multipart/form-data` encoding type, you may encounter the

When sending a request that includes form data object with some data from angular 4 to laravel api, sometimes the request data is received correctly and other times it is null, referred to as 'empty request.' Below are the details of my request: ...

After deploying to Heroku, cal-heatmap encounters errors despite functioning correctly in a local environment

I successfully implemented a cal-heatmap instance in my Angular 2 (angular-cli) project locally, but when I deployed the project to Heroku, I encountered some errors that prevent the cal-heatmap from displaying. https://i.stack.imgur.com/8gY90.png The er ...

Setting base URLs for production and development in Angular 6: A step-by-step guide

As a beginner in Angular, I am looking for a way to set different base URLs for production and development environments. I aim to dynamically configure the base URL to avoid hard-coding it in the index.html file every time I switch between these two enviro ...

Using ngOnChange on a FormGroup in Angular

Is there a way to detect real-time changes in the fields of a FormGroup? My component structure consists of a simple parent-child setup: Parent Component View <my-child [myForm]="myForm"></my-child> Child Component Controller @Input() myFor ...

Cypress: Unable to properly stub API with cy.intercept()

Whenever I utilize the cy.intercept() function, the API fails to stub. cy.intercept("GET", `${API}farm/list`, { body: { statusCode: 200, message: "Request successful", result: seededFarmList, }, }); The way I import the fixture file is as ...

Exploring the Differences Between ionViewWillEnter and ionViewDidEnter

When considering whether to reinitiate a cached task, the choice between ionDidLoad is clear. However, when we need to perform a task every time a view is entered, deciding between ionViewWillEnter and ionViewDidEnter can be challenging. No specific guid ...

Enhancing interface properties with type safety in a function declaration using Typescript

Consider the following scenario: interface Steps { stepOne?: boolean; stepTwo?: boolean; stepThree?: boolean; } let steps: Steps = {}; function markStepDone (step: ???) { steps[step] = true; } markStepDone('anything'); Is there a wa ...

Angular Material datepicker designed for multiple input fields

In my form, I have multiple text box inputs where users enter dates. These fields are populated with values from a single instance of the Angular Material datepicker via TypeScript code. (dateChange)="onDateChange($event) When a user selects a date, such ...

Storage in Ionic and variable management

Hello, I'm struggling to assign the returned value from a promise to an external variable. Despite several attempts, I have not been successful. export class TestPage { test:any; constructor(private storage: Storage) { storage.get('t ...

What is the best way to test a local variable in Angular 2 using karma and jasmine?

I've been working on writing a unit test with jasmine, but I've run into an issue when trying to test a local variable using jasmine. I have successfully tested a global variable in the past, but testing a local variable seems to be more challeng ...

How to set a default option in a dropdown menu using Angular 4

Many questions have been raised about this particular issue, with varying answers that do not fully address the question at hand. So here we go again: In my case, setting the default value of a dropdown select by its value is not working. Why is that so? ...

Interacting Angular 4 Modules communicate with one another

If I have two modules, one for Customers and one for Orders, structured like this: /customers /customers-list.component.html /customers-list.component.ts /customers-details.component.html /customers-details.component.ts /customers-crea ...

How can the '!!user' syntax be utilized? What outcome does this code snippet produce?

I am looking to implement an angular route guard in my application. I came across this code snippet but I am confused about the line where user is mapped to !!user. Can someone explain the purpose of map(user => !!user) in this context? canActivate( ...

Stylishly Select with Bootstrap 4

Currently, I am utilizing Angular 2 with bootstrap 4 and have implemented the following select element: <div class="form-group"> <label class="col-md-4 control-label" for="OptionExample">Choose an option:</label> <div class="c ...

Manipulating variables across various methods in TypeScript

I have a simple code snippet where two variables are defined in the Main method and I need to access them from another method. However, I am encountering an issue with 'variables are not defined', even though I specified them in the declerations ...

The Material Angular components fail to load

Just started a brand new project using Angular and Material design UPDATE : Check out the live editor on StackBlitz: here Working on implementing the toolbar example, but here's what I have so far: Tried inserting the sample code into the app.compo ...

Having trouble utilizing Vue3 methods while utilizing the `<script setup lang="ts">` syntax

Looking to incorporate Vue into a non-Vue Class using the Composition API for a Chrome Extension project where having the entire thing as a Vue App doesn't make sense. The Vue Instance is being instantiated in the usual manner and then injected into ...

Angular CLI 8.2.2 experiencing issues with displaying Themify icons

I recently added Themify icons to my project using npm install --save @icon/themify-icons from https://www.npmjs.com/package/@icon/themify-icons. My method for inserting an image into the site is as follows: <img height="32" width="32" src="@icon/themi ...

Utilize the array map function in a React Native functional component with useState to dynamically render content

I have successfully implemented a functional component that renders a basic form with input elements. My goal is to allow users to dynamically add input elements by clicking a button. To achieve this, I am utilizing the useState hook and have created an o ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...