Search code examples
typescriptangular6typeorm

Saving data from form to database using TypeORM in Angular 6


I'm using TypeORM with angular to save form data to the database. The connection configuration is good as I can save data from the backend

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

I can successfully save to the database running the code below

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));

But I'm presently having issues trying to save data from a form(frontend). Here's my 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 fails to build with tons of errors. Any guide will be helpful


Solution

  • I do this quite different than your approach. I'm using Postgres but that shouldn't matter much but I'm using Nestjs to make it more like Angular. It is a simpler setup than yours but Nestjs shouldn't make much difference either since it barely knows about TypeORM.

    At the top of the controller after imports:

    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')  // /enrollee is the route
    export class EnrolleeController {
      constructor(private readonly EnrolleeService: EnrolleeService) {}
    

    Adding an item, user, whatever in 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;
      }
    

    In the service:

    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);
      }