The function must ensure that any previous functions have completed processing before moving on to the next line of code

Currently, I am facing an issue with TypeScript where I need to call a Modal within a function. The problem arises when a service is called to validate certain data from the server asynchronously. Depending on the response received from the server, I want to either open the modal or skip it entirely. However, due to the asynchronous nature of the server call, the modal ends up opening before the response is received. Is there a way to ensure that the server response is processed first, and then decide whether to open the modal?

For example, in the code snippet below: The CheckandOpenModal function should wait for the completion of the saveRecord method and based on its return value, decide whether to open the modal. Currently, because the control returns to the calling function before receiving the server response, the output remains at 0 and the modal gets triggered.

Any insights on how to tackle this issue would be greatly appreciated.

Here is the main function:

public output:number = 0;
CheckandOpenModal() {
  /* do something */
  this.saveRecord(); // Need to await for this to finish and retrieve output
  if (this.output == 0) {
    // Open the modal window
    const modalRef = this.modalService.open(editTableColComponent, {
      centered: true,
      scrollable: true
    });
  } else {
    // Perform other actions
  }
}

saveRecord() {
    this.serv.checkTableRecord(this.objTableFields.tableNm, this.objTableFields.tableID).subscribe(data => {
      if (data.check.result == 1) {
        this.output = 1;
      }
    });

Answer №1

If you've tagged this question with angular, it seems like you're working with observables for handling async code. The great thing about observables is that they make chaining async operations quite straightforward!

import { map, Observable, tap } from "rxjs";

  checkAndOpenModal(): void {
    this.saveRecord()
      .pipe(
        tap((output) => {
          if (output == 0) {
            const modalRef = this.modalService.open(editTableColComponent, {
              centered: true,
              scrollable: true,
            });
          } else {
            //Do something
          }
        })
      )
      .subscribe();
  }

  saveRecord(): Observable<0 | 1> {
    return this.serv
      .checkTableRecord(this.objTableFields.tableNm, this.objTableFields.tableID)
      .pipe(map((data) => (data.check.result == 1 ? 1 : 0)));
  }

You can also return an observable to continue chaining it elsewhere. Just remember to subscribe at the end of the chain, otherwise no operation will be executed.

checkAndOpenModal(): Observable<1|0> {
  return this.saveRecord()
    .pipe(
      tap((output) => {
        if (output == 0) {
          const modalRef = this.modalService.open(editTableColComponent, {
            centered: true,
            scrollable: true,
          });
        } else {
          //Do something
        }
      })
    );
}

Here's a glossary of the operators used:

  • pipe: allows chaining operators on an observable
  • map: transforms data emitted by the observable
  • tap: executes parallel actions when something is emitted in the observable

For further reference:

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

The functionality of Angular 6 Material Nested Tree is disrupted when attempting to use dynamic data

In Angular 6, I am utilizing mat-tree along with mat-nested-tree-node. My objective is to dynamically load the data when the user toggles the expand icon. Attempting to apply the dynamic data concept from the Flat Tree example provided in Material Example ...

I am sorry, but it seems like there is an issue with the definition of global in

I have a requirement to transform an XML String into JSON in order to retrieve user details. The approach I am taking involves utilizing the xml2js library. Here is my TypeScript code: typescript.ts sendXML(){ console.log("Inside sendXML method") ...

What is the necessity of ngrx/store when services and localStorages are available for use?

When it comes to Angular, we rely on ngrx/store to manage the state. However, I question whether all tasks can be effectively handled using services alone. What benefits does implementing the ngrx/store package offer? Your insights would be greatly appre ...

What are the steps to utilizing services in the MEAN stack framework?

Issue Dealing with a large volume of data has led to performance issues when passing between components using RouterLink, as it triggers database calls through services to MongoDB each time. Code --Institution.component.ts listInstitutions: Institution ...

Issue in Angular when using a shared module: displaying "appears in XXX.module but itself has errors" message

In my Ionic v6 project with Angular, I have developed multiple directives that are needed across various pages. To manage these directives effectively, I have created a shared module: import { MediaPage } from './../directivas/media/media.page'; ...

Exploring the Wonderful World of Styled Components

I have a query regarding styled components and how they interact when one is referenced within another. While I've looked at the official documentation with the Link example, I'm still unclear on the exact behavior when one styled component refe ...

Angular2 RC1 route parameters with periods in them

When working with a child component, I often use paths similar to the following: @Routes([ { path: '/axis/:prefixPath', component: AxisComponent }, ... ]) An example of a resulting link is: http://localhost:3000/parent/axis/foo.bar Th ...

The name "Identifier" has already been declared before

I am currently working on a social network project to enhance my skills in nodejs and reactjs. While debugging the backend code for /signin using Postman, I encountered an error that prevents me from launching the node server. The error message displayed i ...

Using an existing function with no arguments as a handler in Typescript and React: A Step-by-Step Guide

NOTE: I'm still learning Typescript, so I may be missing something obvious here. Let's consider a basic scenario in React Javascript, using a Material-UI Button: // Closing dialog event handler without needing an 'event' argument const ...

The specified field type of Int! was not included in the input

I encountered a GraphQL error that states: "Field JobInput.salarys of required type Int! was not provided." While working on my mutation, I have declared three variables and I'm unsure if the syntax "salarys: number;" is correct. Can someone please c ...

Executing the http.put request twice in Angular2 will result in duplicate data being sent

I'm currently facing an issue with updating a company record through an API in my Angular 2 application. Upon debugging, I noticed that the http call is being triggered twice. I came across a similar discussion on Stack Overflow where the solution was ...

In search of a practical and functional demonstration showcasing Electron v8 combined with TypeScript

Excuse the straightforwardness of my inquiry, as I am reaching the limits of my patience. I am in search of a practical example demonstrating the use of Electron v8 and TypeScript. The example should be simple and functional, without the need for WebPack, ...

Adjusting the height of a div element when scrolling

Is there a way to make a div change size as you scroll? I am trying to achieve an effect like this example: . Currently, I am using Angular's hostListener to capture scroll events and adjust the div accordingly. However, I have been experiencing some ...

How can I substitute a <tr> with my custom component in Angular2+ without disrupting the DOM layout or CSS styling?

Imagine you have a table snippet featuring rows of individuals and their test results: <tr> <td>John Doe</td> <td>18</td> </tr> <tr> <td>Jane Dober</td> <td>28</td> </tr> < ...

Emulating Data in Angular 2 Using Configuration Similar to Ember Mirage

Is there a way to mock data through configuration in Angular 2 similar to how it's done in Ember Mirage? I'm aware that I can create my own solution using Dependency Injection and MockBackend to intercept HTTP calls and provide dummy data. Howeve ...

Error message: It seems that in Angular Universal, the function readFile$().mergeMap is not recognized

Currently, I am integrating Angular Universal server-side rendering into an existing Angular 7 application. As part of this process, I am also attempting to make it work with Firebase. However, in the functions log within the Firebase console, I am encount ...

The custom class-validator decorator in NestJS fails to retrieve the value from the parameter

In my Nestjs project, I have created a Custom ValidatorConstraint using class-validator. The purpose is to create my own decorator and apply it later on DTO classes for validations. Let's consider this route: foo/:client After a request is made, I w ...

Creating a completely dynamic button in Angular 6: A step-by-step guide

I have been working on creating dynamic components for my application, allowing them to be reusable in different parts of the program. At this point, I have successfully developed text inputs that can be dynamically added and customized using the component ...

Alert: Circular dependency detected!

In an effort to have cleaner imports, I've set up a typescript file that exports all the components I'm using. For example: import { Comp1, Comp2, Comp3 } from index/components However, when using this approach, I encounter a warning during bu ...

De-generify the interface

Is it possible to eliminate generics from an interface? Sample code: This is what I currently have: interface ServerMessages { [ActionType.EVENT_1]: ResponseEventBody1; [ActionType.EVENT_2]: ResponseEventBody2; [ActionType.EVENT_3]: ResultModifier ...