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

Steps for converting an observable http request into a promise request

Here is a link to my service file: This is the TypeScript file for my components: And these are the response models: I am currently facing difficulties with displaying asynchronously fetched data in my component's TypeScript file using an Observabl ...

Angular 2's one-of-a-kind singleton solution

I'm feeling a bit lost when it comes to singleton services in Angular 2. I need a translation service that will be accessible throughout the entire application, and I want to ensure that only one instance of the service exists. My issue arises when tr ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

Creating a dynamic text design using Bootstrap or CSS: What's the best approach?

I attempted to enable responsive font sizes in Bootstrap 4.3.1 by setting the $enable-responsive-font-sizes variable to true, but I did not see any changes. Below is the code from my template.html file: <div class="m-2" id="role" ...

Undefined TypeScript Interface

Here's my situation: public retrieveConnections() : IUser[] { let connections: IUser[]; connections[0].Id = "test"; connections[0].Email = "asdasd"; return connections; } I know this might be a dumb question, but why is connecti ...

Can you explain what exactly zone turns refer to?

I recently came across an error message in my Angular 2 application that read: WARNING: your application is taking longer than 2000 Zone turns. This got me thinking, what exactly are 'zone turns' and why does the warning trigger when it exceed ...

Angular 2 Component attribute masking

In my Angular 2 component called Foobar, I have defined a property named foobar: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-foobar', templateUrl: './foobar.component ...

Oops! There seems to be an issue. The system cannot locate a supporting object with the type 'object'. NgFor can only bind to Iterables

onGetForm() { this.serverData.getData('questionnaire/Student Course Review') .subscribe( (response: Response) => { this.questionnaire = response.json(); let key = Object.keys(this.questionnaire); for ...

Using Vuetify to filter items in a v-data-table upon clicking a button

My table structure is similar to this, I am looking to implement a functionality where clicking on the Filter Button will filter out all items that are both male and valid with a value of true. users = [ { name: 'ali', male: true, valid: ...

How to simulate a typescript class using vitest

I am encountering a situation where I have a class A that imports another class B from a separate module and creates an instance of it. While writing tests for class A, I want to stub or mock some of the methods of class B. Below is an example code snippe ...

What is the method for extracting an Ionic image URL from an image that has been uploaded to Firebase?

I'm currently working on uploading an image from a phone in Ionic using Cordova: async takePhoto(sourceType: number) { try { const options: CameraOptions = { quality: 50, targetHeight: 100, targetWidth ...

Navigating with Angular: Transmitting dynamic URL parameters to components

I currently have the following routes defined: const routes: Routes = [ { path: ':product/new', children: [{ path: 'std/:country', component: SignUpComponent, data: { ...

Tips for utilizing chodorowicz / ts-debounce effectively

Looking to utilize the debounce function provided by the ts-debounce package (available at here) in my typescript project. However, struggling to find a concrete example of its usage in typescript. Would greatly appreciate any help or guidance on this ma ...

Exploring diverse paging methods tailored to specific devices within Angular 12

Hey there! I'm looking to implement two different paginations for a single table with 20 rows. Here's what I need: For desktop, the first pagination should display 10 rows on the first page and the remaining 10 rows on the second page. As f ...

Angular 2 - update browsing history by replacing instead of adding to it

Is it possible to replace the history instead of pushing a new one in Angular 2's new router (rc.1)? For instance, suppose I am in a question list (/questions), then open a new modal in a new route (/questions/add). After adding a new question, I nav ...

Waiting for the response from $http in Angular2

In almost all REST requests, I require the user's ID to be included. After logging in a user, I store the token in local storage and pass the ID to user.service.ts (using the function setUserId(userId);). However, when authenticating a user using onl ...

Adding a CSS class to a component element

I am working with an angular component that looks like this: export class HeaderMainComponent { } This is the HTML structure: <header> <nav> <li>Link 1</li> <li>Link 2</li> </nav> </header> ...

Using Angular 4 with Semantic-UI for Dropdown menus

Currently, I am in the process of implementing an Angular directive to handle Semantic UI dropdown. My setup includes Angular (4.3.3), jQuery (3.2.1), and Semantic UI (2.2.13) installed via npm. To make these libraries work together, I made modifications ...

Simple method for wrestling with objects in TypeScript HTTP POST responses

Can anyone help me understand how to extract information from an object received through an HTTP POST request? Below is the code I am using: this.http.post(url, user, httpOptions).subscribe(result => { console.log(result.status); }); The issue aris ...

Simple guide on implementing React with Typescript to support both a basic set of properties and an expanded one

I'm grappling with a React wrapper component that dynamically renders specific components based on the "variant" prop. Despite my efforts, I cannot seem to get the union type working properly. Here's a snippet of the code for the wrapper componen ...