Angular2,按字符串/名称手动解析类型

Ste*_*tes 2 typescript systemjs angular

是否可以通过仅知道它的名称来手动解析组件?

我有一个字符串变量,它将包含一个组件的名称,让我们说"UserService"

我需要能够解决这种类型,我看过Injctor,我可以从文档中看到有一个resolve()resolveAndCreate()(https://angular.io/docs/ts/latest/api/core/Injector-class.html)

但我没有Type.

谢谢

史蒂夫

编辑:尝试以下:

System.import("path/to/service").then(p=>{

     var injector = Injector.resolveAndCreate([p[this.serviceName]]);//works

     var serviceInstance = injector.get(p[this.serviceName]); //Fails with "No provider for Http! (UserService -> Http)".


});
Run Code Online (Sandbox Code Playgroud)

我有Http可用,它是在bootstrap期间提供的,这适用于应用程序的其他部分.

bootstrap(AppComponent, [
    ROUTER_PROVIDERS, Http, HTTP_PROVIDERS, UrlBuilderService,
    provide(LocationStrategy, { useClass: HashLocationStrategy }),
    provide('notification', { useClass: NotificationService })
]);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

进一步编辑:

我现在称之为resolveAndCreate:

var injector = Injector.resolveAndCreate([p[this.serviceName], Http]);
Run Code Online (Sandbox Code Playgroud)

哪个失败了

没有ConnectionBackend的提供者!(UserService - > Http - > ConnectionBackend)

所以我称之为:

var injector = Injector.resolveAndCreate([p[this.serviceName], Http, ConnectionBackend]);
Run Code Online (Sandbox Code Playgroud)

其他一些缺失的东西都失败了.

改成了这个

var injector = Injector.resolveAndCreate([p[this.serviceName], HTTP_PROVIDERS]);
Run Code Online (Sandbox Code Playgroud)

现在一切正常.

我不明白的是为什么它不能自动解析这些组件,因为我在引导期间提供了它们.

Gün*_*uer 5

要按名称获取组件,请导入组件

import * as components from './components'
Run Code Online (Sandbox Code Playgroud)

并使用.访问它们

var componentName = 'SomeComponent';
components[componentName]
Run Code Online (Sandbox Code Playgroud)

另见Rob Wormald的这款Plunker,来自https://github.com/angular/angular/issues/7596#issuecomment-198199074

Injector.resolveAndCreate(
Run Code Online (Sandbox Code Playgroud)

您创建一个新的注入器,它与使用传递给的提供程序从Angular创建的连接器完全断开连接bootstrap(..., [Providers]).
以这种方式创建的注入器只能解析传递给的提供者resolveAndCreate().

如果要使用与Angular应用程序相同的进样器,则需要注入进样器

constructor(private injector:Injector) {
  injector.get(...);
}
Run Code Online (Sandbox Code Playgroud)

您可以从传递的注入器创建子注入器,并根据需要覆盖绑定.在尝试解析请求的依赖项时,子注入器会解析为重写的绑定或向上移动父注入器直到root.