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

时间:2016-02-16 15:36:49

标签: typescript angular systemjs

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

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

我需要能够解析此类型,我已查看Injctor,我可以从文档中看到有resolve()resolveAndCreate()({{3 }})

但我没有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)".


});

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

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

任何想法?

进一步修改

我现在这样称呼resolveAndCreate

var injector = Injector.resolveAndCreate([p[this.serviceName], Http]);

失败

  

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

所以我称之为:

var injector = Injector.resolveAndCreate([p[this.serviceName], Http, ConnectionBackend]);

其他一些遗失的东西都失败了。

已更改为

var injector = Injector.resolveAndCreate([p[this.serviceName], HTTP_PROVIDERS]);

现在一切正常。

我不明白为什么它不能自动解析这些组件,因为我在bootstrap期间提供了这些组件。

2 个答案:

答案 0 :(得分:5)

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

等组件
import * as components from './components'

并使用

访问它们
var componentName = 'SomeComponent';
components[componentName]

另请参阅Rob Wormald

中的https://github.com/angular/angular/issues/7596#issuecomment-198199074来自此Plunker

<强>旧

使用

Injector.resolveAndCreate(

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

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

constructor(private injector:Injector) {
  injector.get(...);
}

如果需要,可以从传递的注入器创建子注入器并覆盖绑定。在尝试解析请求的依赖项时,子注入器会解析为覆盖的绑定或向上传递父注入器直到root。

答案 1 :(得分:4)

你可以通过使用system.js(由angular2使用的加载器)来实现这一点:

System.import('path/to/UserService').then(m => 
{
    //Here you can access user service and use it in injector etc.
    Injector.resolveAndCreate([m.UserService]);
});

本文详细说明了这种技术:Lazy Loading of Route Components in Angular 2