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

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

问题描述

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

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.

我有一个通用类...我们称之为自定义类,我在整个网站中都使用它.然而,这个类是由我实例化的,而不是 angular 2.现在,我需要在该类中使用由 angular 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.

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

Custom 类在许多其他地方被实例化,我喜欢将该依赖项移动到自定义类中.

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) 手动将服务传递到自定义类构造函数中.

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

let x = new Custom(this.userService);

2) 使自定义类也成为服务.然后它将参与 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天全站免登陆