Get angular 2 service inside a custom class instantiated by me

爱⌒轻易说出口 提交于 2019-12-01 12:14:49

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/45469256/get-angular-2-service-inside-a-custom-class-instantiated-by-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!