【问题标题】:How to inject services into other services in Loopback JS?如何将服务注入 Loopback JS 中的其他服务?
【发布时间】:2020-07-16 08:56:48
【问题描述】:

Loopback 框架的新手。

我来自 Angular 和 Java(Spring 框架),这样的模式很常见。

我将如何在 Loopback 中做类似的事情?

@bind({ scope: BindingScope.TRANSIENT })
export class EmailService {
  constructor(
    @service() public environmentService: EnvironmentService,
    @service() public logger: LoggingService,
    public transporter: Mail,
  ) {
    this.setupMailClient()
  }
}

这是我尝试上述方法时遇到的错误:

$ yarn start
yarn run v1.22.4
$ npm run build

> service-email@1.0.0 build /Users/clementoh/projects/service-email
> lb-tsc

$ node -r source-map-support/register .
Server is running at http://[::1]:3000/development/v1/emails
Try http://[::1]:3000/development/v1/emails/ping
Unhandled error in POST /verifications/email: 500 ResolutionError: The argument 'LoggingService.constructor[1]' is not decorated for dependency injection but no value was supplied by the caller. Did you forget to apply @inject() to the argument? (context: RequestContext-x2a2BH0zTmy5OlakULzpvw-3, resolutionPath: controllers.RemoteConfigController --> @RemoteConfigController.constructor[0] --> services.EmailService --> @EmailService.constructor[1] --> services.LoggingService)

【问题讨论】:

    标签: loopback


    【解决方案1】:

    注入服务的语法如下:

    constructor(
        @service(MyService) public myService: MyService
    ) {}
    

    试试吧,如果它不能再次工作,你需要将你的服务绑定到应用程序上下文中,例如在 application.ts 中(或在你的应用程序构造函数上):

    import {MyService} from './services';
    
    constructor(options = ApplicationConfig = {}) {
        super(options);
    
        // Setup
        this.bind('services.my-service').toClass(MyService);
    }
    

    现在您可以通过以前或从此注入您的服务:

    @inject('services.my-service) public myService: MyService
    

    【讨论】:

    • 感谢@lorenzoli 为我指明了正确的方向。我找到了错误的根本原因并发布了答案。尽管如此,我还是会赞成你的回答:)
    【解决方案2】:

    感谢@lorenzoli 为我指明了正确的方向。

    我收到错误的原因是因为我使用 TypeScript 功能在构造函数中定义它们时自动创建类级属性。

    @bind({scope: BindingScope.TRANSIENT})
    export class EmailService {
      constructor(public transporter: Mail) {
        this.setupMailClient()
      }
    }
    

    当我从构造函数中删除该属性时,一切都按预期工作。

    我猜想对于 Loopback,我们不应该使用 Angular 项目中常见的 TypeScript 自动属性创建语法。

    @bind({scope: BindingScope.TRANSIENT})
    export class EmailService {
      public transporter: Mail
    
      constructor() {
        this.setupMailClient()
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 2014-05-07
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多