Answer the question
In order to leave comments, you need to log in
How to initialize a class in typescript?
Hello.
I have class User.service.ts
export class UserService {
public getAllUsers(): DocumentQuery<IUser[], IUser, {}> {
return Users.find() // Возвращает список пользователей
}
}
export class UserController {
constructor(private userService: UserService){} // Тут я пытаюсь проинициализировать класс "Как в Angular"
public index(req: FastifyRequest<IncomingMessage>, reply: FastifyReply<ServerResponse>) {
this.userService.getAllUsers() // Тут я вызываю метод getAllUsers но мне пишет что такого метода нет
.then(users => {
this.users = users
reply.send(this.users)
})
}
}
const userService = new UserService()
Answer the question
In order to leave comments, you need to log in
Because there are still decorators @Injectable
and @Component
others in Angular using Angular 2 DI
and dependency injection
, they register the service class (component, etc.) in the injector, using the class reference as an identifier.
And also look at the parameters of the constructor.
When you request a service in a constructor, the injector looks in its registry and if an instance of the class is found, it passes it to the constructor, and if not, it creates an instance. Those. yours new UserService()
is present but hidden in the decorator.
It is clear that in bare typescript this behavior is not provided.
If you want to use Angular-style tricks on the back-end, then take a look at Nest.js, everything is already set up there, a very suitable backend framework (however, there are others).
If you just want to take the DI mechanism for your project, check out the typedi and Inversify libraries
Your code does not work, because no one passes an instance of the class to your constructor for you.
In Angular, this is done by the IoC container that implements Dependency Injection.
If you need similar functionality, then look for IoC container implementations for JS / TS, for example, inversify.io/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question