The promise chain from the ngbModal.open function is being bypassed

I'm currently working on implementing data editing within a component. My task involves checking if any of the data fields have been altered, and if so, prompting a confirmation pop-up to appear. If the user confirms the change, the data will then be updated.

Within the updateData() method, I am invoking the isChangeConfirmed() function which triggers the pop-up and verifies if the Save button has been clicked. Upon confirmation, it should return true. However, instead of returning control to the updateData() method after this step, the data gets saved first before the pop-up window is displayed. What could be causing this unexpected behavior?

component.html

<button id="saveButton" type="button" (click)="updateData()" translate>BUTTON.SAVE</button>


<!-- POPUP -->

<ng-template #editModal let-modal>
  <button type="submit" id="modalConfirmButton" (click)="modal.close('save')" class="btn btn-primary" translate>BUTTON.CONFIRM</button>
  <button type="reset" id="modalCancelButton" (click)="modal.close('cancel')" class="btn btn-primary" translate>BUTTON.CANCEL</button>
</ng-template>

component.ts

updateData() {
  if (this.isChangeConfirmed()) {

    // Code for updating data goes here

  }
}

isChangeConfirmed(): boolean {
  if (this.oldValue != this.newValue) {
    this
      .ngbModal
      .open(this.editModal, { ariaLabelledBy: 'editModal' })
      .result
      .then((result) => {
        return result == "save";
      }, (reason) => {
        return false;
      });
  }
  return true;
}

Answer №1

Upon opening the modal, there arises a quandary with the sections enclosed within

(result) => { /*asynchronous part*/ }
and
(reason) => { /*asynchronous part*/ }
, as they execute asynchronously. The timing of these executions in relation to the external sections remains indeterminate. Placing your return false; statement within the asynchronous context while positioning the return true; statement outside of it results in uncertainty regarding the execution order. It appears that, in this scenario, return true; executes more expeditiously than return false;. However, the precise sequence of events cannot be predicted.

While the setup may seem acceptable, inserting return true; inside

(result) => {... return true;}
will likely prompt a complaint from the compiler about missing a return statement.

To resolve this issue, two solutions come to mind:

  • Combine all code into one function instead of using a separate function, and place // Some code which updates data inside
    (result) => {... /* Some code which updates data*/ }
  • If you prefer to keep a separate function, alter the return type from boolean to an Observable, then subscribe to that Observable within updateData(). Explore how to combine the responses of (result) and (reason) into a single Observable, create an Observable from this amalgamation, and return it.

If you opt for the second approach, I recommend delving into RxJS Operators (https://rxjs.dev/guide/operators). Additionally, familiarizing yourself with articles on reactive programming can prove beneficial.

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

Utilizing the namespace importation method correctly

How can I efficiently utilize classes from a namespace that may be the same or different from the current file's namespace? I currently have the following two files. TypeA.ts: export namespace Game { @ccclass export class TypeA extends cc.Component ...

How to automatically set focus in a text box when a Kendo Window is opened

I am working on a project where I need to set the focus on the first field of a kendo-window when it opens after clicking on a button. I used ViewChild to declare the field, but it is showing as undefined when the window is opened because it hasn't be ...

What is a way to incorporate two ngClass directives within a single div element?

Is it possible to include two ng-class directives within a single div element? If so, how should we go about writing them together? Thank you for your help. <div [ngClass]={'white-background': policyNumber.length <= 0} [ngClass]="getS ...

The data type 'AbstractControl | null' cannot be assigned to type 'FormGroup'

I am facing an issue with passing the [formGroup] to child components in Angular. The error message says Type 'AbstractControl | null' is not assignable to type 'FormGroup'. I have double-checked my conditions and initialization, but I ...

"Exploring the depths of Webpack's module

This is my first venture into creating an Angular 2 application within MVC Core, utilizing TypeScript 2.2, Angular2, and Webpack. I have been closely following the Angular Documentation, but despite referencing the latest NPM Modules, I encounter errors w ...

Angular 4: Bringing back localstorage data upon user's backbutton navigation

I have a component that handles a list of items. Users can filter the entries using three checkboxes. Clicking on an item takes them to another component where detailed information is displayed. To navigate to the second component, the function used is: ...

How to refresh a specific component or page in Angular without causing the entire page to reload

Is there a way to make the selected file visible without having to reload the entire page? I want to find a cleaner method for displaying the uploaded document. public onFileSelected(event): void { console.log(this.fileId) const file = event.targe ...

The 'toBeInTheDocument' property is not found on the 'Matchers<HTMLElement>' type

Having trouble setting up testing for a components library. Despite trying various examples and similar threads, I have not been successful. I can confirm that my setupTests.ts file is being loaded correctly (verified through a console.log). Additionally, ...

Preventing recursive updates or endless loops while utilizing React's useMemo function

I'm currently working on updating a react table data with asynchronous data. In my initial attempt, the memo function doesn't seem to be called: export const DataTableComponent = (props: State) => { let internal_data: TableData[] = []; ...

Bringing Typescript functions into the current module's scope

Is it possible to import and reference a module (a collection of functions) in typescript without the need for the Module. prefix? For instance: import * as Operations from './Operations'; Can I access Operations.example() simply as example()? ...

Tips for validating an object with unspecified properties in RunTypes (lowercase object type in TypeScript)

Can someone please confirm if the following code is correct for validating an object: export const ExternalLinks = Record({}) I'm specifically asking in relation to the repository. ...

How can Angular send datetime data to Nodejs in the most effective manner?

Working with the primeng calendar component within a template-driven form, I encountered an issue. When passing the date 16/05/2018 11:45 from Angular to Node, it gets converted to 2018-05-16T06:15:33.000Z. I discovered that I could convert it back to IST ...

"Protractor's browser.wait in Angular application fails to wait for the element to be visible

I am encountering an issue with the wrong login message. I am using async spec along with browser.wait to wait for the element to appear in the DOM, but it is not functioning as expected. Instead of waiting for the specified timeout if the element is not p ...

Resolving the problem of Turkish uppercase dotted i when using the capitalization pipe in Angular 2

I have created a custom capitalization pipe that successfully capitalizes almost all characters, including converting the Turkish 'ı' character into 'I'. However, I am facing an issue where the 'i' character is also being con ...

What are the steps to fix the error stating that 'loginError.data' is an unknown type?

Recently delving into typescript, I decided to test the waters with nextjs, rtk query, and antd. However, while attempting to access error within useLoginMutation using the property error.data.message, it was flagged as type unknown. To tackle this issue, ...

Dealing with 'TypeError X is Not a Function' Error in Angular (TypeScript): Occurrences in Certain Scenarios and Absence in Others

Recently, I came across an odd issue in Angular 14 where a type error kept popping up. Although I managed to refactor the code and find a workaround, I'm quite intrigued as to why this issue is happening so that I can prevent it from occurring again i ...

Webpack magic comments are not supported by dynamic import in Angular 8.0

After upgrading from Angular 7 to Angular 8, I observed a downgrade in my webpack version from 4.33.0 to 4.30.0. With the new support for dynamic importing in angular8, I wanted to utilize webpack "magic comments" to customize the chunk name of my angula ...

After a recent deployment, the Angular PWA hosted on a NestJS server experiences unexpected crashes

I have set up an Angular PWA (version 11) on a NestJS (version 7) server. However, after each new deployment, the PWA crashes because the browser attempts to fetch a JavaScript file that no longer exists and then redirects to the root site (html): main.945 ...

How can I achieve the same functionality as C# LINQ's GroupBy in Typescript?

Currently, I am working with Angular using Typescript. My situation involves having an array of objects with multiple properties which have been grouped in the server-side code and a duplicate property has been set. The challenge arises when the user updat ...

Does Angular 16 not provide support for the agm/core module?

Encountering an issue while using Angular 16 with AgmCoreModule. The error message reads: node_modules/@agm/core/lib/core.module.d.ts:25:22 [ng] 25 export declare class AgmCoreModule { [ng] ~~~~~~~~~~~~~ [ng] This indi ...