【发布时间】:2021-07-23 19:50:27
【问题描述】:
是否可以使用带参数的 TypeORM 侦听器?
例子:
@BeforeInsert()
public async doSomething(myImportantParam) {
// using myImportantParam here
}
【问题讨论】:
标签: javascript node.js typescript typeorm
是否可以使用带参数的 TypeORM 侦听器?
例子:
@BeforeInsert()
public async doSomething(myImportantParam) {
// using myImportantParam here
}
【问题讨论】:
标签: javascript node.js typescript typeorm
与@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 ...*/
}
希望这会有所帮助。干杯? !!!
【讨论】:
this 来访问它。