在Nestjs中使用TypeORM作为ORM框架时,需要在app.module.ts文件中导入TypeORM模块,并在app.module.ts文件中配置数据库连接。
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'test',
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
synchronize: true,
}),
],
})
export class AppModule {}
在Nestjs中使用TypeORM时,需要创建实体类。实体类是数据库中表的映射,确保实体类中正确定义了表中的字段和数据类型,并在实体类中定义好了更新数据库的方法。
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 50 })
name: string;
@Column()
age: number;
async save() {
// 更新数据库...
}
}
在Angular中,可以使用HttpClient请求Nestjs中的API,保存数据到数据库中。
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user = {
name: '',
age: 0,
};
constructor(private http: HttpClient) {}
save() {
this.http.post('/user', this.user).subscribe(response => {
console.log(response);
});
}
}
在Nestjs中,可以处理前端发送过来的请求,更新数据库中的数据。