I'm struggling to transfer information from my form to TypeScript in Angular

Currently, I am working on developing a fullstack application using Node.js and Angular (material UI). However, I have encountered an issue that I need help with.

I am trying to figure out how to retrieve data from an Angular form for a small web resource management application. Right now, I am in the process of registering users and storing their information in a MySQL database.

https://i.sstatic.net/liHPd.png

On the server side, we have the following code:

const express = require('express');
const app = express();
var cors = require('cors');
var mysql = require('mariadb');
const body = require("body-parser");
app.use(body.urlencoded({ extended: false }));
app.use(body.json());
app.use(cors());

var connection = mysql.createPool({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'totale',
});

app.get('/', function (req, res) {
  res.send('Hello World!');
  console.log(req);
});

app.post("/inscription",(req,res)=>{
  var nom = req.body.name;
  var prenom = req.body.lastname;
  var mail = req.body.email;
  var password = req.body.password;
  connection.getConnection().then(conn => {
    conn.query("INSERT INTO `inscription` (nom,prenom,mail,password) values (?,?,?,?);",[nom,prenom,mail,password],function(err, rows) {
      if (err) throw err;
      console.log('The solution is: ', rows[0].solution);
      });
  });
});

app.listen(3000, function () {
  console.log('app listening on port 3000!');
});

Here is the HTML form structure:

<form [formGroup]="signupForm" class="example-form" (ngSubmit)="onFormSubmit(signupForm)" novalidate>
  <mat-form-field class="example-full-width">
    <input type="text" id='email' name='email' matInput placeholder="Enter your email"/>
  </mat-form-field>
  <mat-form-field class="example-full-width">
          <input type="text"  id='name' name='name' matInput placeholder="Nom">
  </mat-form-field>
  <mat-form-field class="example-full-width">
           <input  type="text"  id='lastname' name='lastname' matInput placeholder="Prenom" >
  </mat-form-field>
  <mat-form-field class="example-full-width">
          <input type="password" id='password' name='password' type="password" matInput placeholder="Enter your password" [type]="hide ? 'password' : 'text'">
              <button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide">
          </button>
  </mat-form-field>
  <div class="example-button-row">
    <button type="submit" mat-raised-button>Inscription</button>
  </div>
</form>

In TypeScript, we handle the data retrieval like this:

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { User } from './../User';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import {tap} from 'rxjs/operators';
import {NgForm} from '@angular/forms';


@Component({
  selector: 'app-inscription',
  templateUrl: './inscription.component.html',
  styleUrls: ['./inscription.component.css']
})

export class InscriptionComponent implements OnInit {
  signupForm;
  results;


  constructor (private http: HttpClient, private formBuilder: FormBuilder)
  {}
  ngOnInit() {
    this.signupForm = this.formBuilder.group({
      email :"",
      name :"",
      lastname :"",
      password :"",
    });
  }
  public onFormSubmit() {
    const configUrl = 'http://localhost:3000/inscription';
    this.http.post(configUrl,this.signupForm.value)
    .pipe(
      tap(
        data => console.log(configUrl, data),
        error => console.log(configUrl, error)
      )
    )
    .subscribe(results => this.results = results);
 }
}

Answer №1

Ensure that you include the formControlName attribute in all your form fields.

To make sure your form data is accessible in your ts file, modify your form as shown below:

<form [formGroup]="signupForm" class="example-form" (ngSubmit)="onFormSubmit(signupForm)" novalidate>
  <mat-form-field class="example-full-width">
    <input type="text" id='email' name='email' formControlName="email" matInput placeholder="Enter your email"/>
  </mat-form-field>
  <mat-form-field class="example-full-width">
          <input type="text"  id='name' name='name' formControlName="name" matInput placeholder="Nom">
  </mat-form-field>
  <mat-form-field class="example-full-width">
           <input  type="text"  id='lastname' name='lastname' formControlName="lastname" matInput placeholder="Prenom" >
  </mat-form-field>
  <mat-form-field class="example-full-width">
          <input type="password" id='password' name='password' formControlName="password" type="password" matInput placeholder="Enter your password" [type]="hide ? 'password' : 'text'">
              <button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide">
          </button>
  </mat-form-field>
  <div class="example-button-row">
    <button type="submit" mat-raised-button>Inscription</button>
  </div>
</form>

Answer №2

Here's a quick tweak for the onFormSubmit function.

public onFormSubmit() {
    const configUrl = 'http://localhost:3000/registration';
    this.http.post(configUrl,this.signupForm.value)
    .subscribe(response => {
        this.response = response;
    });
 }

Also, remember to include console.log(req.body) on the API side. If you're still not receiving data, double check the configuration and provide detailed error descriptions if necessary.

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

Leveraging import and export functionality in TypeScript while utilizing RequireJS as a dependency

I am in the process of transitioning a complex JavaScript application from Backbone/Marionette to TypeScript. While making this shift, I want to explore the benefits of exporting and importing classes using files as modules. Is it necessary to incorporat ...

Boost the Gen 2 User Directory

After reviewing all of the Amplify Gen 2 Documentation, I am struggling to find a way to display a list of registered users within my application. I need to create an admin page in Angular that will showcase all users along with their respective roles. I ...

Is it possible to enable tooltips to function through the innerHTML method?

Currently, I am utilizing the innerHTML attribute to modify the inner HTML of a tag. In this instance, it involves the <td></td> tag, but it could be applied to any tag: <td *matCellDef="let order" mat-cell [innerHTML]="order. ...

Having trouble locating a character's name in the Marvel API with NodeJS

I have integrated the Marvel API to fetch character data using axios. Here is a snippet of the code I am using: const axios = require('axios'); const md5 = require('blueimp-md5'); const publickey = '73f5271b4d972dc0f4eba'; co ...

Guidelines for Organizing Angular Interface Files and Implementing Custom Type Guards

In my Angular 2 project, I am utilizing Interfaces and have implemented User Defined Type Guards: grid-metadata.ts export interface GridMetadata { activity: string; createdAt: object; totalReps: number; updatedAt: object; } grid.service.ts ... ...

Utilize express/node to iterate through requests sent to the NOAA API

I have developed an API middleware for my company to pull information from the NOAA API and store it in my database. The process works as expected, but the challenge arises when trying to handle information based on zip codes one at a time. Each request fe ...

Sending an array from an external JavaScript file to a specific route

Currently, I am developing an application using Node.js with Express that displays images from a database. I am now focusing on implementing the feature to create albums from the displayed images by clicking on them. The IDs and names of the images are st ...

The autoimport feature is not supported by the Types Library

My latest project involves a unique library with only one export, an interface named IBasic. After publishing this library on npm and installing it in another project, I encountered an issue. When attempting to import IBasic using the auto-import feature ( ...

Why does the pound symbol in z-index always show up in Angular?

Having an issue with my code where I set a z-index in the CSS like this: .mat-mini-fab { position: absolute; right: 5px; top: 4px; z-index: 999; box-shadow: none !important; } However, whenever I visit my site, the z-index is not being appl ...

What are the advantages of using HttpClient compared to fetch?

With the introduction of Angular 2+, HttpClient now facilitates HTTP requests sent down an RxJS observable. I'm curious about why one would opt for using HttpClient's API instead of the standard fetch for individual HTTP requests. I have a good ...

What are some strategies I can implement to effectively manage different errors and ensure the app does not crash

I came across a variety of solutions for error handling. The key concept revolves around this explanation: https://angular.io/api/core/ErrorHandler Attempts were made to implement it in order to capture TypeError, however, the outcome was not successful: ...

What steps can I take to successfully implement form posts in my Nodejs application on cpanel?

Hey there, I am currently facing an issue with my Node.js/Express application. I have a form in an HTML file that works perfectly fine on my local machine. The form.html is located in a public folder and below are the form attributes along with a submit bu ...

Having trouble verifying a user's password in Postman using "bcrypt.compareSync" with Angular and the MEAN stack

I'm currently working on implementing user authentication before adding a JWT token, and I've encountered an issue where the 'if' check is generating this error: node_modules\bcryptjs\dist\bcrypt.js:265 th ...

Guide to creating a functional Async API

I am currently facing a challenge while developing an application for my institution. I need to allow users to access database information (currently using firebase) from an external server, so I set up a node.js server to facilitate communication and hand ...

Having trouble launching the node pm2 process manager on AWS Elastic Beanstalk, npm update verification did not pass

Having some issues with utilizing pm2 for managing processes in my typescript node application, deployed on elasticbeanstalk. Whenever a new instance is launched by pm2, the following shows up in the logs ---------------------node.js logs---------------- ...

Troubleshooting issue with doctrine association mapping and ArrayCollection persistence error

Let's discuss the following problem: There is a many-to-one relationship between Article and Author. class Author{ /** * ... *@var ArrayCollection_of_Article */ public $articles; } class Article{ /** * ... *@var Author ...

Issue encountered during the installation of express

Encountered the following error during express installation. Currently running node 0.10.17 and npm 1.3.8 Tried npm install express Seems to be a version compatibility issue. What is the recommended version? npm ERR! Error: shasum check failed for C:&b ...

What is the best way to open a new page on top of the current page using Angular2?

On the left side of my page, I have two menu items - "Dashboard" and "Resource request". You can easily switch between them by clicking on each item. Both pages are separate components. I'm looking to change the functionality a bit. I want to add a b ...

What is the most effective way to retrieve data using Mongoose in a service function?

I am currently facing an issue with my node application service that involves using nodemailer to send emails with links to clients. The problem arises when trying to query the recipient email address using Mongoose in the service, as I receive a respons ...

Next.js Issue: Invariant error - page not correctly generated

I encountered a recurring error while attempting to build my project. Strangely, everything runs smoothly during development, but as soon as the build process is initiated, the following error presents itself: next build ▲ Next.js 14.1.0 - Environm ...