A
A
Alexander Sharomet2019-06-28 11:23:27
Node.js
Alexander Sharomet, 2019-06-28 11:23:27

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() // Возвращает список пользователей
    }
}

And the User.controller.ts class
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)
                    })
    }
}

When I try to call the getAllUsers() property of the UserService class, I get the error Cannot read property 'getAllUsers' of undefined.
But if I declare a class like this, then everything works. Why is this happening? After all, a similar approach works in Angular. Thank you.
const userService = new UserService()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2019-06-28
@sharomet

Because there are still decorators @Injectableand @Componentothers 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

P
Pavel Pikat, 2019-06-28
@PavelPikat

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 question

Ask a Question

731 491 924 answers to any question