我正在使用带角度的typeorm将表单数据保存到数据库。连接配置很好,因为我可以从后端保存数据
{
"type": "mssql",
"host": "***",
"port": ***,
[...]
"entities": [
"src/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
[...]
}
我可以将以下代码成功保存到数据库中
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));
但是我目前在尝试从表单(前端)保存数据时遇到问题。这是我的代码
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));
}
该项目无法建立,并产生大量错误。任何指南都会有所帮助
答案 0 :(得分:1)
我的做法与您的做法完全不同。我正在使用Postgres,但这没什么大不了,但是我正在使用Nestjs使它更像Angular。这是一个比您的设置简单的设置,但是Nestjs也不会有太大的区别,因为它几乎不了解TypeORM。
导入后位于控制器顶部:
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) {}
添加项目,用户,无论在控制器中是什么
@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;
}
在服务中
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);
}