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.

4
  • May I ask why the Custom class can't be an Angular service as well? Commented Aug 2, 2017 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 Commented Aug 2, 2017 at 20:03
  • It seems it still could be an Angular service? Commented Aug 2, 2017 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. Commented Aug 2, 2017 at 20:56

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.