Storing information from a form into a database with the help of TypeORM on Angular 6

Utilizing TypeORM alongside Angular to store form data in the database has been successful. The connection configuration is correct, allowing for data storage from the backend.

{
   "type": "mssql",
   "host": "***",
   "port": ***,
   [...]
   "entities": [
      "src/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   [...]
}

The process of saving to the database functions well with the following code:

import "reflect-metadata";
import {createConnection} from "typeorm";
import {User} from "./entity/User";
[...]    
createConnection().then(async connection => {    
    console.log("Inserting a new user into the database...");
    const user = new User();
    user.firstName = "Timber";
    user.lastName = "Saw";
    user.age = 25;
    await connection.manager.save(user);
    console.log("Saved a new user with id: " + user.id);
    
    console.log("Loading users from the database...");
    const users = await connection.manager.find(User);
    console.log("Loaded users: ", users);
         
}).catch(error => console.log(error));

However, I am facing difficulties in saving data from a frontend form. Here's my current code:

SubmitForm() {
//initialize connection with the database
this.connection.then(async connection=> {
  console.log("Inserting a new user into the database...");
  //create a new enrollee
  let enrollee = new Enrollee();
  enrollee.enrolleeTitle = this.PDTitle;
  enrollee.enrolleeLastName = this.PDSurname;
  enrollee.enrolleeFirstName = this.PDFirstname;
  enrollee.enrolleeOtherName = this.PDMiddlename;
  [...]
  let enrolleeRepo = connection.getRepository(Enrollee);

  //save info into database
  await enrolleeRepo.save(enrollee);
 console.log("Saved a new user with id: " + enrollee.id);
  //get all enrollees
  console.log("Loading enrollees from the database...");
  let enrollees = await enrolleeRepo.find();
  console.log("Loaded errollees: ", enrollees);
}).catch(error => console.log(error));
}

The project compilation fails with numerous errors. Any assistance or guidance would be greatly appreciated.

Answer №1

My approach to this problem differs from yours in several ways. I am utilizing Postgres as my database, although the choice of database management system should not have a significant impact on the overall solution. Additionally, I have incorporated Nestjs into my project to enhance its similarity to Angular. Despite this, the setup is relatively straightforward, and the inclusion of Nestjs does not heavily rely on TypeORM integration.

Within the controller file, following the necessary imports, the code structure is as follows:

import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  HttpException,
  HttpStatus,
  Body,
  Req,
  HttpCode,
  Param, Query
} from '@nestjs/common';
import { EnrolleesService } from './enrollees.service';
import { Enrollees } from './enrollees.entity';

@Controller('api/enrollee') // The route for this controller
export class EnrolleeController {
  constructor(private readonly EnrolleeService: EnrolleeService) {}

For adding an item or user within the controller:

@Post()
  async addItem(@Req() req, @Body() recordData): Promise<Enrollees> {

    const result: Enrollees = await this.EnrolleesService.addItem(recordData);
    if (!result)
      throw new HttpException('Error adding new Enrollee', HttpStatus.BAD_REQUEST);
    return result;
  }

Regarding the service component:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getManager, getRepository } from 'typeorm';
import { Enrollees } from './enrollees.entity';


@Injectable()
export class EnrolleesService {

  private entityManager = getManager();

  constructor(
    @InjectRepository(Enrollees)
    private readonly enrolleesRepository: Repository<Enrollees>
  ) {}

  async addItem(recordData): Promise<Enrollees> {
    return await this.enrolleesRepository.save(recordData);
  }

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

Overloading TypeScript functions with Observable<T | T[]>

Looking for some guidance from the experts: Is there a way to simplify the function overload in the example below by removing as Observable<string[]> and using T and T[] instead? Here's a basic example to illustrate: import { Observable } from ...

Encountering Error when Attempting to Load Webpack Dependencies for Browser

I'm currently in the process of manually scaffolding an Angular 6 app (not using the CLI). Everything was going smoothly until I encountered a webpack error: ERROR in window is not defined After researching online, it seems like I may be missing som ...

Exploring the capabilities of using the injectGlobal API from styled-components in a TypeScript

I've been attempting to utilize the simple injectGlobal API, but I am encountering difficulties getting it to work with TypeScript. Here is my setup in theme.tsx: import * as styledComponents from "styled-components"; import { ThemedStyledComponentsM ...

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 ...

Accessing router params in Angular2 from outside the router-outlet

I am currently working on a dashboard application that includes a treeview component listing various content nodes, along with a dashboard-edit component that displays editable content based on the selected branch of the tree. For example, the tree struct ...

Typeorm encountered an error when attempting to assign the unknown type to an entity

I'm encountering difficulties while using TypeOrm with TypeScript for a specific project. It appears that TypeScript is unable to recognize a type being returned from a TypeORM entity. @Entity({ name: "users", synchronize: false }) export default c ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

What methods are available for altering state in Server Actions in NextJS 13?

Struggling to Implement State Change in NextJS 13 Server Actions I have encountered a challenge with altering state within the execution of server actions in NextJS 13. The scenario involves an actions.ts file located at the root of the app directory. Cur ...

Angular 5 - Jasmine Tests explained: Encounter with the puzzling error message: "Error: Provider for the NgModule 'DynamicTestModule' is invalid, as only instances of Provider and Type are permitted"

I'm having trouble running tests on a component class. Here's the error message from the stack: Error: Invalid provider for the NgModule 'DynamicTestModule' - only instances of Provider and Type are allowed, got: [AlertModaldataCompon ...

Protected members in Angular 2 component templates using TypeScript

Reflecting on ways to incorporate members in a component that can be accessed from the template but not from a parent component sparked my curiosity. In exploring TypeScript visibility in Angular 2, I encountered discussions about "public" and "private" d ...

Managing conflicting versions of React in a component library created with Webpack and Storybook

My goal is to create a React component library on top of MUI using Storybook and TypeScript. Since Storybook is based on Webpack (which includes SASS files), I'm utilizing Webpack to build the bundle because TSC can't compile those files. Subsequ ...

Material UI autocomplete is not detecting the options parameter as an array

I am currently working on implementing an autocomplete field that retrieves options from my component's state, which in turn fetches data from the backend. Here is a snippet of my component: export const Person: React.FC<PersonProps> = ({name, a ...

The MUI component received props that were not defined

I created a customized MUI card with the intention of applying a dark background when the darkBg prop is passed. However, I've encountered an issue where despite passing darkBg as true, the card's background remains white. To troubleshoot, I atte ...

Angular - Customizing button bindings for various functions

As a newcomer to Angular and TypeScript, I am faced with the task of creating a customizable button that can display text, an icon, or both. For example: button-icon-text-component.html <button> TEST BUTTON </button> app.component.html & ...

Extending Interfaces Using Keys from an Array in Typescript

When dealing with a scenario where you want a pointfree omit, you can achieve this: type PlainObject<T> = {[key: string]: T} const omit = <K extends string>( name: K ) => <T, U extends PlainObject<T> & { [P in K]: T }>( ...

defining data types based on specific conditions within an object {typescript}

Can someone help with implementing conditional function typing in an object? let obj = { function myfunc (input: string): number; function myfunc (input: number): string; myfunc: function (input: string|number):string|number { ... } } I've been ...

Exploring the customization options for Prime NG components is a great way to

Currently, I am working on a project that involves utilizing Prime NG components. Unfortunately, the p-steps component does not meet one of our requirements. I am looking to customize the Prime NG p-steps component to fit our needs. Is there a way to cre ...

Unable to execute function: Angular 7 Platform-Browser-Dynamic (intermediate value) share is not defined

Recently, I have been working on upgrading our Angular 5 build to version 7. After installing webpack 4, rxjs 6.3.3, and angular 7.0.3, along with taking care of dependencies, I managed to successfully compile the bundle. However, a puzzling error seems to ...

Encountering difficulties with a custom Firestore service when attempting to extend it after updating to Angular 9

My custom class that wraps Angular Firestore is designed to be extended and used throughout my application. However, after updating to Angular 9, this setup no longer functions properly. For the complete code snippet, visit . The abstract class wrapper: ...

What is the best way to adjust the Material Drawer width in Reactjs to match the width of its children?

Currently, I am utilizing the Material-ui Drawer component to toggle the display of content on the right side of the screen. The functionality I am aiming for is that when the Drawer opens, it will shrink the existing content on the right without any overl ...