简体   繁体   English

如何从另一个控制器调用 Loopback4 控制器的方法

[英]How to call Loopback4 controller's method from another controller

I have a loopback 4 controller with a function that I don't want to expose via HTTP.我有一个带有我不想通过 HTTP 公开的功能的环回 4 控制器。 I would like to be able to call the function from another controller.我希望能够从另一个控制器调用该函数。

How can I do this?我怎样才能做到这一点? Is there any way of injecting a controller in another controller?有没有办法在另一个控制器中注入一个控制器? (I 'm able to inject repositories in controllers, but not controllers in other controllers). (我可以在控制器中注入存储库,但不能在其他控制器中注入控制器)。

You have to first import repository of another controller eg您必须首先导入另一个控制器的存储库,例如

import { MemberRepository, EmailTemplateRepository } from '../repositories';

then you have to inject it in constructor like this:-然后你必须像这样在构造函数中注入它:-

@repository(EmailTemplateRepository) public emailTemplateRepository: EmailTemplateRepository,

then after you can use any function of controller like this:-然后你可以像这样使用控制器的任何功能:-

const template = await this.emailTemplateRepository.findOne({
  where: {
    slug: 'user-password-reset',
    status: 1
  }
}); 

答案在这里: https : //github.com/strongloop/loopback-next/issues/3028

@inject(‘controllers.AnotherController’) c: AnotherController

Ok I figured out how to make this work.好的,我想出了如何使这项工作。 You have to import the @repository component where the rest of the other import statements are, like so:您必须在其他导入语句所在的位置导入 @repository 组件,如下所示:

import { repository } from '@loopback/repository';从'@loopback/repository'导入{存储库};

Adding this, will allow for, @repository(EmailTemplateRepository) public emailTemplateRepository: EmailTemplateRepository, to work.添加这个,将允许,@repository(EmailTemplateRepository) public emailTemplateRepository: EmailTemplateRepository,工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM