Im building an angular 2 app, and i need a way to get a reference to a service/class that is injected/instantiated by angular framework.
I have a generic class...lets call it Custom class, that i use throughout the site. This class, however is instantiated by me, not angular 2. Now, i need to use some of the services instantiated by angular 2 inside that class.
i.e
// this is not angular component/service
export default class Custom {
constructor(properties) {
}
doSomething() {
// UserService is a service that is injected into other componetns constructors, but this class is not a component.
// Here i need a ref to the singleton 'UserService' made by angular
let userService = someAngularFunction.getInstance('UserService');
userService.doIt();
}
}
// in some component.
export class MyComponent implements OnInit {
doAnotherThing() {
let c = new Custom('some generic params');
c.doSomething();
}
}
// in some n number of other components, repeat the above.
Note, i know that i could inject the 'UserService' into MyComponent, and from MyComponent, pass it down to new Custom() constructor. But, since MyComponent itself doesn't use that service, and
Custom class is instantiated in many other places, id like to move that dependency into Custom class.
Is there a way to do that ? If not, whats the second best option.
As far as I know you have two choices:
1) Manually pass the service into the Custom class constructor.
let x = new Custom(this.userService);
2) Make the Custom class a service as well. Then it will participate in Angular's DI.
See this article for more information: https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html