[英]How can I dynamically create a service in Angular?
I am trying to dynamically instantiate services during runtime given a string name (ie reflection). 我正在尝试在运行时给定一个字符串名称(即反射)来动态实例化服务。 Something like:
就像是:
let myService = new window[myClassName](myParams);
Or, alternatively: 或者,或者:
let myService = Object.create(window[myClassName].prototype);
myService.constructor.apply(myService, myParams);
I have looked at Injector
class, but it requires a type, instead of a string ( https://angular.io/api/core/Injector ) . 我看过
Injector
类,但它需要一种类型,而不是字符串( https://angular.io/api/core/Injector )。
Any thoughts on how to accomplish this? 关于如何实现这一目标的任何想法?
You can still use the Injector in combination with strings. 您仍然可以将Injector与字符串结合使用。 It's just a matter of providing your providers in the way you want to use them.
只是以您想要使用它们的方式向您的提供程序提供问题。 This is the example on the Angular page: https://angular.io/api/core/Injector#example-1
[provide: Square]
is short for [provide: Square, useClass: Square]
(you can use useFactory
instead of useClass
when you want to instantiate the service yourself) You can change the first param ( provide
) by basically any Symbol you want, so also string. 这是Angular页面上的示例: https
[provide: Square, useClass: Square]
[provide: Square]
是[provide: Square, useClass: Square]
(您可以使用useFactory
代替useClass
当你想自己实例化服务),您可以更改第一个参数( provide
由基本上任何你想要的符号),所以也字符串。 Have a look at this POC I set up https://stackblitz.com/edit/angular-mg1ezb 看看我设置的这个POC https://stackblitz.com/edit/angular-mg1ezb
你可以试试
instance = new window["yourClassName"]();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.