What are some ways to streamline this repetitive angular code using promises?

As a newcomer to Angular development, I'm curious if there's a more elegant way to streamline the repetitive code shown below.

addTransaccion() {
    try {
      if (this.idTransaccion === '0') {
        this.transaccionesSrv.addTransaccion(data)
          .then(res => {
            if (res) {
              this.router.navigate(['/cuentas/transacciones'], { queryParamsHandling: "preserve" });
            }
          });
      } else {
        this.transaccionesSrv.actualizarTransaccion(data, this.idTransaccion)
          .then(res => {
            if (res) {
              this.router.navigate(['/cuentas/transacciones'], { queryParamsHandling: "preserve" });
            }
          });
      }
    } catch (error) {
      this.envioFormularioOk = false;
    }
  }

Answer №1

perhaps something along these lines


if (this.idTransaccion === '0') {
   this.transaccionesSrv.addTransaccion(data)
      .then(res => {
          if (res) {
              this.router.navigate(['/cuentas/transacciones'], { queryParamsHandling: "preserve" });
          }
      });
} else {
   this.transaccionesSrv.actualizarTransaccion(data, this.idTransaccion))
      .then(res => {
          if (res) {
              this.router.navigate(['/cuentas/transacciones'], { queryParamsHandling: "preserve" });
          }
      });
}

although I find it more challenging to interpret

Answer №2

function handleTransaction(data) {
 if (this.transactionId === '0') {
    return transactionsService.addTransaction(data);
 } else {
    return this.transactionsService.updateTransaction(data, this.transactionId);
 }
}

function goToPage(response) {
 if (response) {
    this.router.navigate(['/accounts/transactions'], { 
       queryParamsHandling: "preserve" });
   }
}

function addTransaction() {
  handleTransaction(data)
  .then(response => goToPage(response))
  .catch((error) => {
    this.formSubmissionSuccess = false;
  });
} 

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

Tips for resolving issues with mat-autocomplete during scrolling

When I open the mat-autocomplete and scroll down the page, I would like for the mat-autocomplete to stay in place. ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

Incorporating properties of the parent class through Mixin techniques

I'm encountering an issue while trying to access a property from an inherited class within a mixin class BaseItem{ public id:string; constructor(id:string) { this.id =id; } } abstract class ConfigMixin<K extends BaseItem& ...

Navigating an array using ngFor and encountering an error message saying, "Identifier not specified"

While using ngFor to iterate through an array, I encountered the following error message: "Identifier 'expenseitem' is not defined. The component declaration, template variable declarations, and element references do not contain such a memb ...

Converting nested arrays to objects via JSON transformation

I am faced with a nested JSON array structure like this: Parent: { Child1: [ {name:'grandchild1', value:'abc', checked:true}, {name:'grandchild2', value:'pqr', checked:false} ], Ch ...

Encountering a validation error when attempting to submit the form

I am facing an issue with my form. Inside the form, I have a dropdown menu that dynamically displays a textbox upon selection. The form also includes an array feature to allow for multiple textboxes to be displayed. Despite filling in all fields with value ...

The NavBar element is failing to update when the state changes

I have been working on developing a shopping cart feature. As I implemented a context and passed the state as a value to increment and decrement buttons in the cart, everything seemed to be functioning well with item counts adjusting accordingly. However, ...

fill the designated column in accordance with the specific criteria

Is there a method to automatically fill in a specific column based on certain conditions? I am looking to populate the column labeled [Last] when the column index is 1 and the corresponding name is [First]. import {Component, OnInit} from '@angular ...

Angular 8 implementation of a responsive readonly input text field styled with Bootstrap 4

I want to make the input text read-only using Bootstrap. After some research on the Bootstrap website, I discovered that the form-control-plaintext class can be used for this purpose. <input type="text" readonly class="form-control-plaintext" id="stat ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

Change TypeScript React calculator button to a different type

I am currently troubleshooting my TypeScript conversion for this calculator application. I defined a type called ButtonProps, but I am uncertain about setting the handleClick or children to anything other than 'any'. Furthermore, ...

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

Customize the file name for exporting data from a Syncfusion grid view with Angular

In my Angular (v6.8) application, I have implemented a Syncfusion grid view from Syncfusion. When downloading the grid content as an Excel sheet, the default file name displayed is "Export.xlsx". I am trying to set a custom file name for the download proce ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

The Angular 2 application successfully loads the JSON file and the HTML structure, however, there seems

I successfully connected an external json file and used ngFor to loop through nested objects on the website. However, I am facing an issue where no data is being displayed. I have attempted to structure the data using an interface but still encounter the p ...

Developing in TypeScript with styled-components allows for seamless integration between

New to TypeScript and seeking guidance. I currently have a component utilizing styled-components that I want to transition to TypeScript. import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-comp ...

Connecting to an unfamiliar attribute of a div element using Angular 12

Looking to dynamically change the value of an attribute in my component using property binding. <div class="app-container" [data-theme]="theme"> <router-outlet></router-outlet> </div> import { Component } from ...

Issue with Angular 6 Snap-to-Component Directive's Functionality in Chrome Browser

I have developed a Snap-to-Component Directive that functions perfectly in Firefox but encounters issues in Chrome. I have checked canIUse and it should be compatible, so I am seeking insights, especially regarding cross-browser compatibility. Your input i ...

Discovering ways to retrieve the complete HTTP response in Angular to access certain response headers

In my angular app, I need to check for specific response headers to handle JWT validation. If a user tries to access a route that requires a valid JWT with an expired token, the back-end ASP.NET Core server will have a response header token-expired: true. ...

Event for Angular 4 mat-datepicker triggering on date selection change

I currently have a date picker feature implemented in my application. Here is the code snippet: <mat-form-field> <input mdInput [matDatepicker]="dp3" placeholder="Select Birthday" name="birthday" disabled> <mat-datepicker-toggle ...