S
S
Sergei Iamskoi2018-07-02 15:31:56
Angular
Sergei Iamskoi, 2018-07-02 15:31:56

How to inject a service into a data class?

With DI in components, everything is clear - angular automatically injects them if they are specified in the constructor. But what if the service is needed in a data class, for example, some

class user {
id: number;
name: string;
constructor(id: nubmer, name: string) {
this.id = id;
this.name = name;
}
get address(){
/* someService */
}
}

First, the constructor is already taken here. And even if it is replaced with a factory function that gives the same instance, then auto-injection will not work in this class because it is created through new. Having googled the solution, we got such a crutch: in the constructor, specify:
let injector = ReflectiveInjector.resolveAndCreate([UserService]);
User.userService = injector.get(UserService);

Are there any other options for solving the problem?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question