Typescript 在环回4中使用服务

Typescript 在环回4中使用服务,typescript,loopback4,Typescript,Loopback4,抽象地说 如何使用环回4服务生成器并创建本地服务类来处理*.repository或*.controller 详细信息 我正在开发一个系统,它需要外部API来获取数据、复杂的哈希/加密等,而不属于控制器范围或存储库范围(为了干净的代码)。Loopback 4使用CLI命令lb4服务生成服务,这方面的文档记录得很差。如何在/service文件夹中创建一个类,导入(或注入或绑定)并像使用存储库一样使用它的方法 ex: 从服务调用方法,如this.PasswordService.encrypt('som

抽象地说

如何使用
环回4
服务生成器并创建本地服务类来处理
*.repository
*.controller

详细信息

我正在开发一个系统,它需要外部API来获取数据、复杂的哈希/加密等,而不属于控制器范围或存储库范围(为了干净的代码)。Loopback 4使用CLI命令
lb4服务
生成
服务
,这方面的文档记录得很差。如何在
/service
文件夹中创建一个类,导入(或注入或绑定)并像使用存储库一样使用它的方法

ex:

从服务调用方法,如
this.PasswordService.encrypt('some text')

this.TwitterApiService.getTweets()
是在
/service
目录中定义的

好的,我自己解决了这个问题。我将按照我遵循的步骤对此进行解释

  • 创建文件夹
    /src/service
    ,并在其中创建
    myService.service.ts
    index.ts
    ,与
    controller
    repository
    等中的文件夹相同(或使用
    lb4 service
    并选择
    local service class
    )。注意:如果您想要实现接口,您可以

  • 使用
    BindingKey.Create()
    方法创建绑定键

  • 将服务注入到所需的类中。在这里,我注入到一个控制器
  • 现在,您可以像
    this.myService.getData(someInput)
    这样访问您的服务了

    export const MY_SERVICE = BindingKey.create<ServiceClass>('service.MyService');
    
    export class NoboBackend extends BootMixin(
      ServiceMixin(RepositoryMixin(RestApplication)),
    ) {
      constructor(options: ApplicationConfig = {}) {
        super(options);
        ...
    
        //add below line
        this.bind('service.MyService').toClass(ServiceClass);
    
        //and code goes on...
        ...
    }
    
    export class PingdController {
      constructor(
        @inject(MY_SERVICE ) private myService: ServiceClass,
      ) {}
      ...
      ...
    }