Let's say I have an abstract service like bellow
abstract class AbstractService {
@InjectConnection() connection: Connection
}
and UserService will extends AbstractService
class UserService extends AbstractService {
async get () {
this.connection //undefined
}
}
I cannot access the connection when I extend AbstractService but it works with a single class
class UserService {
@InjectConnection() connection: Connection
async get () {
this.connection //mongoose connection
}
}
and I call UserService#get in the controller
@Controller(ROUTER.USER)
export class UserController{
constructor(private readonly service: UserService) { }
@Get()
get() {
return this.service.get
}
}
when
UserServiceextendsAbstractServiceit will extend all its members such as methods or constructor but it will not do forconnectionbecause it is a decorator that has to be injected that is whythis.connectionisundefinedin the first example, so you have to deal with that.in the second example,
UserServicedoes not extend anything and has its ownconnectionso it works that's obvious, but we need to extendAbstractServiceso we can use its methods.one solution is to make
UserServicehas its ownconnection, and once created call the parent class constructor passingconnectionto it.in this case, the
get()method will return the expected connection: