是否可以使用带参数的 TypeORM 监听器?
例子:
@BeforeInsert()
public async doSomething(myImportantParam) {
// using myImportantParam here
}
最佳答案
如 @BeforeInsert文档,它不允许您向监听器添加任何参数。
但是,我相信您可以为您的实体创建一个构造函数,该构造函数将 myImportantParam
作为参数,并且您可以使用 this.myImportantParam
访问监听器中的值。
下面是一个示例代码(假设myImportantParam
是一个字符串)。
实体类:
@Entity()
export class Post {
constructor(myImportantParam: string) {
this.myImportantParam = myImportantParam;
}
myImportantParam: string;
@BeforeInsert()
updateDates() {
// Now you can use `this.myImportantParam` to access your value
foo(this.myImportantParam);
}
/*... more code here ...*/
}
服务等级:
export class PostService {
async addNewPost() {
const myImportantParam = 'This is what I need!';
const post = new Post(myImportantParam);
// Add any other properties the post might have
/*... more code here ...*/
// Insert the updated post
await getRepository(Post).insert(post);
}
/*... more code here ...*/
}
希望这对您有所帮助。干杯🍻!!!
关于javascript - 带有参数的 Typeorm 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67334396/