0

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.

Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42
  • May I ask why the Custom class can't be an Angular service as well? – DeborahK Aug 02 '17 at 19:35
  • Custom class is basically a Model with various functions, like save(), update(), sort() etc These models are created in a service, after some content is loaded from the server. e.g a contentService loads a list of post( raw data ), and builds ContentModels from the raw data. Then, these content models are provided to components through observable subscriptions. in some component i can do this. contentService.load().subscribe( (posts) => { this.posts = posts; }) And in some component functions i'd do this.posts[3].save() or in template (click)="post.delete()" etc – Rainer Plumer Aug 02 '17 at 20:03
  • It seems it still could be an Angular service? – DeborahK Aug 02 '17 at 20:05
  • You may be able to use `@Inject(UserService) private userService` in the constructor of the class, although I'm not sure on that. – Jason Spradlin Aug 02 '17 at 20:56

1 Answers1

0

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

DeborahK
  • 57,520
  • 12
  • 104
  • 129