Is there a specific function that is triggered upon the successful completion of a subscription process?

I am facing an issue with the code below. The navigation is happening when a customer is created, instead of waiting for the address to be created successfully. Any assistance on this matter would be greatly appreciated.

createCustomer(model: any) {
        let isSuccess:boolean=true;
        this.loading = true;
        this.errorMsg = "";
        this.createCustomerService.createCustomer(model).subscribe(res => {
          this.tempCustomer = res;
          console.log("Returned Response is");
          console.log(this.tempCustomer);
          if (model.addressType.home.street_address) {
            this.createCustomerService.addAddress(this.tempCustomer.id, "HOME", model.addressType.home, model.cc).subscribe(res => {
            },
              err => {      
                this.errorMsg = err;
                this.alertService.error(err);
                this.loading = false;
              });
          }
          if (model.addressType.work.street_address) {
            this.createCustomerService.addAddress(this.tempCustomer.id, "WORK", model.addressType.work, model.cc).subscribe(res => {
            },
              err => {
                this.errorMsg = err;
                this.alertService.error(err);
                this.loading = false;
              });
          }
          if (model.addressType.other.street_address) {
            this.createCustomerService.addAddress(this.tempCustomer.id, "OTHER", model.addressType.other, model.cc).subscribe(res => {
            },
              err => {
                this.errorMsg = err;
                this.alertService.error(err);
                this.loading = false;
              });
          }

        },
          err => {
            this.errorMsg = err;
            this.alertService.error(err);
            this.loading = false;
          },
          () => this.router.navigate(['/pages/searchcustomer']));

        // if (!this.errorMsg) {
        //   this.router.navigate(['/pages/searchcustomer']);
        // }
      }
    }

Answer №1

if you want to execute multiple observables concurrently, you can utilize the forkJoin method

once all Observables have completed, the subscribe function in forkJoin will be invoked

ob1 = this.createCustomerService.addAddress(this.tempCustomer.id, "HOME", model.addressType.home, model.cc);
ob2 =  this.createCustomerService.addAddress(this.tempCustomer.id, "WORK", model.addressType.work, model.cc)
ob3 = this.createCustomerService.addAddress(this.tempCustomer.id, "OTHER", model.addressType.other, model.cc)

    Observable.forkJoin([ob1, ob2,ob3]).subscribe(results => {
      // results[0] represents ob1
      // results[1] represents ob2
      // results[2] represents ob3
    });

It is important to note that I am assuming these observables are one-time calls. If they are not, consider using Zip

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

Angular2 is designed to break down complex applications into smaller, more manageable parts

Need for a Solution Recently, I was given responsibility of overseeing a large, legacy web application at work that involves multiple scrum teams and development teams. One major issue we face with this application is that whenever one team makes updates ...

Update an API call to switch from promises to observables, implementing axios

Recently, I have been experimenting with using rxjs for API requests in a React application and this is the approach that I have come up with. What are your thoughts on this method? Are there any best practices that you would recommend following? If you ...

Imitating elegant angular input styles

Just before launch, the higher-ups have decided that they prefer a modern aesthetic for input controls - underlines rather than boxes, with labels that slide out of the way when the input is in focus. Check out the effect on this page: https://material.an ...

There seems to be an issue with AngularJS $locationProvider.html5Mode not functioning properly in

My goal is to remove the hashtag from my ui-router URLs. I've found that http://localhost:3000/email doesn't work, but http://localhost:3000/#email does. Despite searching on Stack Overflow, I haven't been able to find a solution that works ...

Encountering an error with the Angular 2 SimpleChanges Object during the initial npm start process

Within my Angular 2 application, there exists a component that holds an array of objects and passes the selected object to its immediate child component for displaying more detailed data. Utilizing the "SimpleChanges" functionality in the child component a ...

Passing dynamic values to nested components within an ngFor loop in Angular

I'm currently facing an issue with a child component inside a ngFor loop where I need to pass dynamic values. Here is what I have attempted so far, but it doesn't seem to be working as expected <div *ngFor="let item of clientOtherDetails& ...

Utilizing electron as a development dependency in an Ubuntu environment

After installing electron on Ubuntu 17.10, this is the process I followed: ole@mki:~/angular-electron$ npm i --save-dev electron > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9bcb5bcbaadabb6b799e8f7eef7e8eb"> ...

Unable to access API hosted on localhost from Angular Client integrated with C# Backend running on a standalone server unit

I have an Angular Client (v14) and a .Net 6 WebAPI running on separate projects within a Raspberry Pi. The setup is for a standalone kiosk where both the front end and backend are hosted on the same device. My goal is to access the front end from a PC on ...

Upgrading to Angular 14 has caused issues with component testing that involves injecting MAT_DIALOG_DATA

After upgrading Angular from 14.1.1 to 14.2.10 and Material from 14.1.1 to 14.2.7, a peculiar issue arose when running tests with the default Karma runner. I am at a loss as to what could have caused this problem, so any advice would be appreciated. The u ...

What is the approach to constructing an observable that triggers numerous observables depending on the preceding outcome?

One of my endpoints returns { ids: [1, 2, 3, 45] }, while the other endpoint provides values for a given id like { id: 3, value: 30, active: true }. I am currently attempting to create an observable that will call the first endpoint and then, for each id r ...

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...

Sending data to templates in Angular 2 using @Input()

I can't seem to figure out what I'm doing wrong with my listing template. I am trying to make it more dynamic by passing parameters using []="" and @Input(). Here is an example: <div class="listing wrapper"> <div class="wrapper" ...

The response of the Typescript Subscription function

I'm struggling with retrieving the subscribe array in NG2. Being new to typescript, I find it difficult to understand how to pass variables between functions and constructors. This is what my code currently looks like: export class RosterPage exten ...

Angular 5 - capturing form inputs - activating event upon selecting suggested values

When I click on suggested values below the input field, the (click)="doSomething()" event doesn't fire. How do I handle this issue? I would like to be able to type something in the input field and then have an event triggered when clicking on the su ...

Strategies to prevent fortuitous success in testing

I have the following test case: it('is to display a welcome message', () => { spyOnProperty(authServiceSpy, 'token').and.returnValue(environment.testAuthenticationToken); let teacher: Teacher = authServiceSpy.token.teacher; ...

Troubles with Conditional Application of CSS Styles to a Twitter-Bootstrap Table

I am facing an issue with highlighting a row in a table when a barcode is entered. Despite following similar scenarios and checking my code, the CSS doesn't seem to be applied. Can anyone help me figure out what I'm missing or how I can fix this? ...

Instruct the main component to retrieve updated information

Within my parent component, there is a router outlet containing a component that generates new objects associated with the parent. I'm unsure how to notify the parent component to make a new API call for updated data. Can you assist me in understandin ...

Angular 6 combined with Firebase is experiencing difficulties with routing after a successful login

After spending hours trying to fix my issue, I still can't figure it out. I've searched through related threads on SO, but haven't found a solution yet. Issue After successfully signing up, the email verification flag is set to true. Howev ...

Troubleshooting issues with accessing the _id property using Typescript in an Angular application

Encountering an Angular error that states: src/app/components/employee/employee.component.html:67:92 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is ...

Tips for removing the notification that the .ts file is included in the TypeScript compilation but not actively used

After updating angular to the latest version 9.0.0-next.4, I am encountering a warning message even though I am not using routing in my project. How can I get rid of this warning? A warning is being displayed in src/war/angular/src/app/app-routing.modul ...