Injecting a model into a service
Our first User
model is now setup. Of course, we will have to inject it into a service or even a controller. To inject a model anywhere else, we must first create the appropriate provider in order to give it to the module.
This provider will define the key to use in order to inject it and take as a value the User
model that we have implemented before.
export
const
userProvider
=
{
provide
:
'UserRepository'
,
useValue
:User
};
To inject it in into a service we will use the @Inject()
decorator, which can take the string defined in the previous example UserRepository
.
@
Injectable
()
export
class
UserService
implements
IUserService
{
constructor
(
@
Inject
(
'UserRepository'
)
private
readonly
UserRepository
:typeof
User
)
{
}
...
}
After injecting the model into the service, you will be able to use it to access and manipulate the data as you want. For example, you can execute this.UserRepository.findAll()
to register the data...