在我实例化的自定义类中获取angular 2服务 [英] Get angular 2 service inside a custom class instantiated by me

查看:100
本文介绍了在我实例化的自定义类中获取angular 2服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个角度2应用程序,我需要一种方法来获取由角度框架注入/实例化的服务/类的引用。

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.

我有一个通用的类...让我们称之为自定义类,我在整个网站中使用它。然而,这个类是由我实例化的,而不是有角度的2.
现在,我需要在该类中使用由角度2实例化的一些服务。

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.

ie

// 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.

注意,我知道我可以将' UserService '注入
MyComponent ,并从 MyComponent 将其传递给 new Custom()构造函数。但是,由于MyComponent本身不使用该服务,并且

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

自定义类在许多其他地方实例化,id喜欢移动该依赖项进入自定义类。

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)手动将服务传递给Custom类构造函数。

1) Manually pass the service into the Custom class constructor.

let x = new Custom(this.userService);

2)使Custom类也成为一项服务。然后它将参与Angular的DI。

2) Make the Custom class a service as well. Then it will participate in Angular's DI.

有关更多信息,请参阅此文章: https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2。 HTML

See this article for more information: https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html

这篇关于在我实例化的自定义类中获取angular 2服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆