【问题标题】:How to call a method of a class which has dependency injection in Loopback 4 (typescript)?如何在 Loopback 4(打字稿)中调用具有依赖注入的类的方法?
【发布时间】:2022-01-09 13:03:49
【问题描述】:
export class CronController {
    constructor(
        @service() public syncService: SyncService,
    ) { }

    async cron() {
        this.syncService.pitSyncCompanies();
    }
}   

@injectable({scope: BindingScope.TRANSIENT})
      export class SyncService {
        constructor(
            @repository(CompanyRepository) public companyRepository: CompanyRepository,
        ) { }
    
        async pitSyncCompanies() {
            console.log('Hi');
        }
    }

如何实例化 CronController 以调用方法 cron()? 我不能只创建 object = new CronController() 因为它的构造函数接受参数,我不确定在这里传递什么。 如何在 Loopback 4 (typescript) 中调用具有依赖注入的类的方法?

【问题讨论】:

  • this. syncService.pitSyncCompanies()。不确定依赖注入与问题有何关系..
  • 我已经修改了问题。在这里,我如何创建 CronController 的对象?因为它的构造函数需要@service() public syncService: SyncService
  • 你不应该调用new,你需要从依赖注入容器/上下文或者在这个框架中调用它来获取它。查看文档

标签: typescript dependency-injection loopback4


【解决方案1】:

通常,框架会启动绑定的“初始解析”(例如,在 HTTP 请求中,框架会解析适当的 REST 控制器,然后会启动必要依赖项的解析树) .

如果您想自己“启动”解决方案(即没有来自框架本身的任何触发器),您可能正在寻找createProxyWithInterceptors()。当您编写的代码在上下文之外时,这在极少数情况下很有用。

例如:

// This does not bind `CronController` to Context.
// It also assumes that the Context has the necessary...
// bindings already added to it (i.e. `SyncService`).

// If the app already depends on `@loopback/core`, import...
// from that package instead for consistency. `@loopback/core`...
// re-exports `@loopback/context`.

import {createProxyWithInterceptors} from '@loopback/context';

createProxyWithInterceptors(CronController, myContextHere);

需要注意的是,这个函数的返回值是一个AsyncProxy,与原来的类不是严格类型兼容的。

重要的是,这对于大多数用例来说不是必需的,主要用于自定义 Server 实现。

在使用 @loopback/rest 的内置服务器实现的典型 REST 项目中,您将在 REST 控制器中解析 CronController,如下所示:

// This example uses Constructor Injection, but Property- and Parameter Injection are supported as well.
// This example also assumes that `CronController` was bound using `this.add(createBindingFromClass(CronController))` in the Application/Context constructor
export class MyRESTController {
  constructor(
    @inject(CronController)
    cronController: CronController
  ) { }
}

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 2020-03-15
    • 2017-01-06
    • 2017-07-31
    • 2016-10-26
    • 2016-01-06
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    相关资源
    最近更新 更多