簡體   English   中英

如何調用在 Loopback 4(打字稿)中具有依賴注入的 class 的方法?

[英]How to call a method of a class which has dependency injection in Loopback 4 (typescript)?

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() 因為它的構造函數接受 arguments 我不知道在這里傳遞什么。 如何調用在 Loopback 4(打字稿)中具有依賴注入的 class 的方法?

通常,框架將啟動綁定的“初始解析”(例如,在 HTTP 請求中,框架將解析適當的 REST Controller,然后啟動必要的依賴樹解析)。

如果您想自己“啟動”解決方案(即沒有來自框架本身的任何觸發器),您可能正在尋找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);

需要注意的是,這個 function 的返回值是一個AsyncProxy ,與原來的 class 沒有嚴格的類型兼容。

重要的是,這對於大多數用例來說不是必需的,並且主要用於自定義服務器實現。

在使用@loopback/rest的內置服務器實現的典型 REST 項目中,您將在 REST Controller 中解析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
  ) { }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM