How to call Loopback4 controller's method from another controller

£可爱£侵袭症+ 提交于 2020-06-17 16:45:27

问题


I have a loopback 4 controller with a function that I don't want to expose via HTTP. 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).


回答1:


You have to first import repository of another controller e.g.

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
  }
}); 



回答2:


Answer is here: https://github.com/strongloop/loopback-next/issues/3028

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



回答3:


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:

import { repository } from '@loopback/repository';

Adding this, will allow for, @repository(EmailTemplateRepository) public emailTemplateRepository: EmailTemplateRepository, to work.



来源:https://stackoverflow.com/questions/56408784/how-to-call-loopback4-controllers-method-from-another-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!