【问题标题】:Typeorm listeners with parameters带参数的 Typeorm 监听器
【发布时间】:2021-07-23 19:50:27
【问题描述】:

是否可以使用带参数的 TypeORM 侦听器?

例子:

@BeforeInsert()
public async doSomething(myImportantParam) {
    // using myImportantParam here
}

【问题讨论】:

    标签: javascript node.js typescript typeorm


    【解决方案1】:

    @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 来访问它。
    • 这正如我所愿,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    相关资源
    最近更新 更多