使用 Loopback 4 中的服务

Sal*_*tha 5 typescript loopback4

摘要

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

详细

我正在开发一个需要外部 API 来获取数据、复杂的散列/加密等不属于控制器范围或存储库范围的系统(为了干净的代码)。Loopback 4lb4 service需要生成CLI 命令,但service文档记录不足。如何在/service文件夹中创建一个类并导入(或注入或绑定或其他)并使用它的方法,就像我们对存储库所做的那样?

前任:

从服务中调用方法this.PasswordService.encrypt('some text') 目录this.TwitterApiService.getTweets()中定义的方法/service

Sal*_*tha 6

好吧,我自己想通了。我将按照我遵循的步骤解释这一点。

  1. 创建的文件夹/src/service和里面创建myService.service.tsindex.ts作为相同controllerrepository等等(或使用lb4 service和选择local service class)。注意:如果你想实现接口,你可以。

  2. 使用BindingKey.create()方法创建绑定密钥。

export const MY_SERVICE = BindingKey.create<ServiceClass>('service.MyService');
Run Code Online (Sandbox Code Playgroud)

ServiceClass 可以是类或接口。

  1. 转到application.ts并将密钥(此处为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...
    ...
}
Run Code Online (Sandbox Code Playgroud)
  1. 将服务注入你想要的类。在这里我注入一个控制器
export class PingdController {
  constructor(
    @inject(MY_SERVICE ) private myService: ServiceClass,
  ) {}
  ...
  ...
}
Run Code Online (Sandbox Code Playgroud)

现在您可以像this.myService.getData(someInput)...一样访问您的服务!