在我实例化的自定义 class 中获取 angular 2 服务
Get angular 2 service inside a custom class instantiated by me
我正在构建一个 angular 2 应用程序,我需要一种方法来通过 angular 框架获取对 service/class 的 injected/instantiated 的引用。
我有一个通用的 class...我们称之为 Custom class,我在整个站点中都使用它。这个class不过是我实例化的,不是angular2。
现在,我需要在 class 中使用 angular 2 实例化的一些服务。
即
// 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 本身不使用该服务,并且
Custom class 在许多其他地方实例化,我想将该依赖项移动到 Custom class.
有办法吗?
如果没有,第二好的选择是什么。
据我所知你有两个选择:
1) 手动将服务传递到自定义 class 构造函数中。
let x = new Custom(this.userService);
2) 也使自定义 class 成为一项服务。然后会参与Angular的DI。
有关详细信息,请参阅本文:https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html
我正在构建一个 angular 2 应用程序,我需要一种方法来通过 angular 框架获取对 service/class 的 injected/instantiated 的引用。
我有一个通用的 class...我们称之为 Custom class,我在整个站点中都使用它。这个class不过是我实例化的,不是angular2。 现在,我需要在 class 中使用 angular 2 实例化的一些服务。
即
// 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 本身不使用该服务,并且
Custom class 在许多其他地方实例化,我想将该依赖项移动到 Custom class.
有办法吗? 如果没有,第二好的选择是什么。
据我所知你有两个选择:
1) 手动将服务传递到自定义 class 构造函数中。
let x = new Custom(this.userService);
2) 也使自定义 class 成为一项服务。然后会参与Angular的DI。
有关详细信息,请参阅本文:https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html