Whenever a call to `http.put` is made, it is certain that

I am facing an issue with my form in Angular 2. When the user clicks on the submit button, I intend to send the data to a rest endpoint using the http module. Here is the structure of the form:

<form novalidate [formGroup]="formGroup()" (ngSubmit)="send()">

  <input (change)="enableThree($event.target.checked)" 
  formControlName="one" type="checkbox"  />

  <input (change)="disable($event.target.checked)" 
  formControlName="two" type="checkbox"  >

  <input formControlName="three"type="text"  >

  <input  formControlName="four"  type="text"  >

  <input  formControlName="five" type="text"  >

  <input  formControlName="six" type="number" > 

    <button>Go</button>

</form>

Here is the component responsible for the functionalities:

import {    Component,    OnInit} from '@angular/core';
import {    FormBuilder,    FormGroup,    FormControl} from '@angular/forms';
import { MyService } from '../my.service';

@Component({
    selector: 'my-form',
    templateUrl: './form.component.html',
    styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {

    private readonly fb: FormBuilder;
    private readonly myForm: FormGroup;
    private data: any;
    private myService : MyService;

    constructor(formB: FormBuilder, myService : MyService) {
        this.myService = myService;
        this.fb = formB;
        this.myForm = this.fb.group({
            thre: [{
                value: "",
                disabled: true
            }],
            four: new FormControl(""),
            five: new FormControl(""),
            six: new FormControl(""),
            one:new FormControl(""),
            two:new FormControl("")
        });

    }

    // Methods to handle form functionalities

}

And the service class for handling HTTP requests:

import { Injectable } from '@angular/core';
import {    Http,    Response,    Headers,    RequestOptions} from '@angular/http';
import { Entity } from './entity';

@Injectable()
export class MyService {

    // HTTP request methods

}

However, I am facing an issue where the update functionality triggers an unexpected HTTP post request in addition to the put request. This issue does not occur when adding or deleting entities. Also, the console.log message in the send() function is only printed once.

If you have any tips or suggestions on how to resolve this issue, I would greatly appreciate it. Thank you!

Answer №1

Essentially, when you format your code correctly, it will appear like this:

 if (this.data.one) {
    this.updateData();
 }


 if (this.data.two) {
   this.deleteData();

 }else {
    this.addData();
 }

but this format does not yield the desired outcome.

The correct structure for your if statement is actually

  if (this.data.one) {
     this.updateData(); 

  } else if (this.data.two) {   //*** Pay attention here    
      this.deleteData();

  } else {
      this.addData();
  }

the key addition here is the else if

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 first argument passed to CollectionReference.doc() must be a string that is not empty

I'm facing an issue with my Ionic app while attempting to update records in Firebase. The error message I keep encountering has me stumped as to where I might be going wrong. Error: Uncaught (in promise): FirebaseError: [code=invalid-argument]: Functi ...

Alert displaying NextJS props

I recently began learning Next.js and have encountered an issue while trying to pass props from a parent component to a child component. The error message I'm seeing is: Type '({ name }: { name: any; }) => JSX.Element' is not assignable ...

Custom JavaScript files are not recognized by Angular 4 pages unless the page is manually refreshed

I am facing an issue with my custom JavaScript files in Angular. I have imported them all in the angular-cli.json file but the pages do not recognize them unless I refresh the page after navigating from one page to another. Here is a snippet of my angular ...

Angular error message: The property 'results' is not found on the type 'ICandidate'

I am currently working with Angular-12 and have the following code snippet: Interface: export interface ICandidate { id: number; first_name: string; other_name: string; last_name : string; email: string; gender : string; user_photo: any; m ...

Challenges managing errors in Angular unit tests

As I continue to learn Angular, my search for information has yielded minimal results. However, one resource that stood out was a post on Stack Overflow titled How to write a test which expects an Error to be thrown in Jasmine? After reviewing the aforeme ...

When using Angular, the onSelectionChange event is not triggered for angular mat-option components

I am working with a mat-form-field that includes both an input field and a mat-autocomplete feature with mat-options. The input field has a (blur) event triggered when it loses focus, while the mat-option has an (onSelectionChange) event triggered when an ...

The data structure of '(string | undefined)[]' cannot be matched with type '[string | undefined]'

I've been working on a TypeScript project and I've encountered the ts(2322) error as my current challenge. Here's a snippet of my code: import { BASE_URL, AIRTABLE_BASE_ID, AIRTABLE_TABLE_STUDENT, AIRTABLE_TABLE_CLASSES, API_KEY, ...

Break down the key:value objects into individual arrays

I'm currently working on an ionic project that involves handling an incoming array composed of key:value objects such as the one shown in the image below: https://i.stack.imgur.com/qrZiM.png My question is, can these values be separated into three d ...

What is the best way to line up changing column values with changing row values in an HTML table?

In its current state, the data appears as follows without alignment: https://i.sstatic.net/o5OLu.jpg The data columns are housed within a single variable due to the presence of multiple excel tabs with varying columns. Within the tr tag, rows are checked ...

Error encountered with TypeScript template literals strings type

There's a new feature in the latest version of Typescript that allows the use of template literal strings as types, like this: type Hey = 'Hey'; type HeyThere = `${Hey} There`; It works perfectly in the Typescript playground with version 4 ...

Is your Angular EventEmitter failing to emit events?

I seem to have a confusion about how the EventEmitter works. I want to execute a function on a custom component when a focusout event occurs. Here is the code from my custom-form.component.html: <div class="flex flex-col"> < ...

Issues have been encountered with the Angular Bootstrap accordion animation not functioning properly when closing in a production

After setting up Bootstrap in Angular app, I encountered an issue in production. When using the accordion feature with animation, the closing animation does not work when I run ng build --configuration production and view it on the local server. The openin ...

When a radio button is clicked in Angular7 and it shares the same form control name, both radio buttons are being

Visit this StackBlitz link for more information. places = ['effil tower','new discover'] new FormGroup({place: new FormControl()}); <div *ngIf="places?.length > 0" class="col-12"> <div style=" padding-top: 1e ...

No TypeScript error in Angular app when assigning a string to a number data type

Today, I encountered some confusion when my app started acting strangely. It turns out that I mistakenly assigned a string to a number without receiving any error alerts. Any thoughts on why this happened? id:number; Later on: this.id = ActiveRoute.params ...

Struggling to retrieve the 'this' object using a dynamic string

Within my Nuxt + TS App, I have a method that attempts to call a function: nextPage(paginationName: string): void { this[`${paginationName}Data`].pagination .nextPage() .then((newPage: number) => { this.getData(pagination ...

The module "<file path>/react-redux" does not contain an exported member named "Dispatch"

Currently, I am in the process of following a TypeScript-React-Starter tutorial and have encountered an issue while wrapping a component into a container named Hello.tsx. Specifically, at line 4, the code snippet is as follows: import {connect, Dispatch} ...

Using ng-bootstrap in Angular to filter a JSON object for a typeahead feature

Hello, I am currently working on implementing a typeahead feature in Angular using ng-bootstrap. To achieve this, I have set up a service to fetch JSON data from the server. import { Search } from './search'; export const SEARCH: Search[] = [ ...

Utilize static information within an Angular component

I'm working on an Angular project in my localhost and I want to have two routed components that share the same data. One component will display the data, while the other will handle the data. In simpler terms, I need two webpages: one with an input f ...

Error: "the cart variable in the ctx object has not been defined"

A project I'm currently working on involves a pizza ordering app, and my current focus is on implementing the Cart feature. Each user has their own cart, which includes specific details outlined in cart.ts import { CartItem } from './cartitem&a ...

Executing a function after a subscriber has finished in Angular 8+

Welcome fellow learners! Currently, I am diving into the world of Angular and Firebase. I am facing an interesting challenge where I fetch ticket data from my collection and need to add new properties to it. However, the issue arises when my ordering funct ...