Ways to verify if a function has completed execution and proceed to invoke another function

I am seeking to verify if a user has chosen an item from the ngFor form and then redirect them to another page upon submitting the form with the updated value.

HTML:

<mat-select placeholder="Treatment" [(ngModel)]="model.TreatmentA" name="TreatmentA" #TreatmentA (change)="onChange(TreatmentA.value)"
 disableRipple>
    <mat-option value="Sutent (Sunitinibum) 25mg">Sutent (Sunitinibum) 25mg</mat-option>
    <mat-option value="Sutent (Sunitinibum) 37.5mg">Sutent (Sunitinibum) 37.5mg</mat-option>
    <mat-option value="Sutent (Sunitinibum) 50mg">Sutent (Sunitinibum) 50mg</mat-option>
</mat-select>

<div class="row">
            <button mat-raised-button color="primary" type="submit" value="submit">Update Patient</button>
            <button mat-raised-button color="accent" (click)="goBack()">Cancel</button>
          </div>

TS

private onChange(TreatmentAValue): any {
    console.log(TreatmentAValue);
}

onChangeSubmit(){
    const CONDITION = true;
    const DATA = this.onChange(this.TreatmentAValue);
    const ERROR = new Error(this.goBack())

    const promise =
        new Promise((resolve, reject) => {
            // do some async stuff
            this.router.navigate(['/patient/ra', this.id]);

            if (CONDITION) resolve(DATA);
            else reject(ERROR);
        })

    updatePatient() {
        this.patientService
            .updatePatient(this.model)
            .subscribe(() => this.onChangeSubmit());

    }
  model = new Patient();
  id = this.route.snapshot.params['id'];
  private getSinglePatient(): any {
    this.patientService
        .getPatient(this.id)
        .subscribe(patient => {
          this.model = patient[0];
        })
  }
    }

In summary, I need to confirm if a selected treatment value has changed for a specific field, and then direct the user to the desired component only if they have selected a new treatment from the list when submitting the form...

Answer №1

To ensure your original and changed values are stored separately, you can create distinct variables for each like so:

originalTreatment: any;
newTreatment: any;

Then, in your onChange() method, assign the new value as shown below:

private onChange(newTreatmentValue): any {
    this.newTreatment = newTreatmentValue;
}

Finally, to compare the values and check for differences, you can do the following:

onChangeSubmit(){
    const DIFFERENCE = this.originalTreatment !== this.newTreatment;
    const CHANGES = this.onChange(this.newTreatment);
    const ISSUE = new Error(this.goBack());

    const promise =
        new Promise((resolve, reject) => {
            // perform asynchronous operations
            this.router.navigate(['/patient/treatment', this.id]);

            if (DIFFERENCE) resolve(CHANGES);
            else reject(ISSUE);
        });

    updatePatient() {
        this.patientService
            .updatePatient(this.model)
            .subscribe(() => this.onChangeSubmit());
    }
}

If needed, feel free to adjust the code based on your specific data structures.

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

Nexus and GraphQL: The root typing path for the "context" type is not found

I’m currently working on integrating GraphQL into Next.js API routes. For writing the GraphQL schema, I’m utilizing Nexus. Here are the two essential files: context.ts and schema.ts, that help in setting up Nexus development mode. // context.ts import ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

The cdkDropList in Angular's drag and drop feature does not support the application of element styles

Just wanted to share my experience in case it helps someone else out there! I've been working on an Angular project where I needed to create a Trello-like application. To enable dragging elements from one list to another, I installed the Angular cdk ...

Strategies for Populating Objects in Angular 2

I have a created a complex class hierarchy with multiple classes. I need assistance with populating the "OptionsAutocomplete" object in angular2. Can someone please provide guidance on how to achieve this? interface IOpcionesAutocomplete { opciones ...

What are the steps to conduct a health check for an Angular container that is powered by Node.js?

Looking to conduct a healthcheck for an Angular container. Below is the Dockerfile: FROM node:18-alpine as builder RUN npm install -g @angular/cli WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build:ssr FROM node:18-alpine WORKDIR /a ...

What is the best way to output data to the console from an observable subscription?

I was working with a simple function that is part of a service and returns an observable containing an object: private someData; getDataStream(): Observable<any> { return Observable.of(this.someData); } I decided to subscribe to this funct ...

What's the best way for me to figure out whether type T is implementing an interface?

Is it possible to set a default value for the identifier property in TypeScript based on whether the type extends from Entity or not? Here's an example of what I'm trying to achieve: export interface Entity { id: number; // ... } @Compon ...

Guide on adding up the value of a property within an array of objects using AngularJS

I am receiving an array of results from a Node.js API in my Angular app, and here is how it looks: <div *ngFor="let result of results"> <div *ngIf="result.harmattan.length > 0"> ... </div> <br> .. ...

Wrapper functions that are nested are returning a Promise that resolves to another Promise of type T

I have a function called doesPromiseyThings that wraps a thunk and returns its value inside a Promise. I want to create another wrapper that not only handles the creation of thunks, but also ensures the returned type is a Promise-wrapped version of the ori ...

Error Type: Jest: A transform is required to have a `process` function in order for it to

Encountering an error while running 'npm test': FAIL __tests__/unit/domain/services/demo-service.ts ● Test suite failed to run TypeError: Jest: a transform must export a `process` function. at ScriptTransformer._getTransformer ( ...

Typescript polymorphism allows for the ability to create various

Take a look at the following code snippet: class Salutation { message: string; constructor(text: string) { this.message = text; } greet() { return "Bonjour, " + this.message; } } class Greetings extends Salutation { ...

What is the best way to extract data from Azure Data Lake and showcase it within an Angular-2 interface?

I am facing a challenge where I need to retrieve files with content from Azure Data Lake and display them in an Angular-2 Component. The issue is that when using the List File Status() method, I am only able to obtain file properties, not the actual conten ...

Issue: Multiplying values within an array in TypeScript requires that the left-hand side of the arithmetic operation must be of type 'any', 'number', or 'enum'

Having trouble with Typescript as I encounter this error message The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362) Specifically facing issues when trying to multi ...

Incorporate a fresh element into an object after its initial creation

Hello, I am looking to create an object in JavaScript that includes an array-object field called "Cities." Within each city entry, there should be information such as the city's name, ID, key, and a District array object containing town data for that ...

Troubleshooting the excessive time taken for Angular Material tree re-rendering

I am currently using mat-tree with large data sets in child nodes retrieved from an API call, with each child node containing around 3k records. My approach involves updating the dataSource by adding the children from the API under the existing dataSource ...

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...

Creating dynamic components from JSON elements does not trigger a rerender of components within an array

Imagine having a simplified input structure like this: [ { type: "text", text: "how are you {name}" }, { type: "input", input: "name" }, { type: "text", text: "good to ...

What might be the reason behind Array concatenation causing an issue in TypeScript?

I am relatively new to TypeScript and recently encountered an issue while working with classes. class DataStorage { private data:string[] = []; addItem(item: string){ this.data.push(item); } removeItem(item: string){ ...

Can you explain how the "reduce" function can be implemented using an interface in TypeScript?

Can you explain the "reduce" function using an interface in TypeScript? https://i.stack.imgur.com/X1VxL.png ...

Ecommerce Template for Next.js

I am new to the world of web development and I have a project involving customizing a Next.js ecommerce template. Since I'm still learning programming, I would appreciate a simple summary of the steps I need to take in order to achieve this. The speci ...