-1

我有几个要包含在模块中的类,因此我可以只导入模块,因为它是一个不同的包,并从中使用这些类。这是一个小例子:

human.ts(我的类文件)

export class Human {

  private numOfLegs: Number;

  constructor() {
    this.numOfLegs = 2;
  }
}

test.module.ts(我的模块文件)

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { Human } from './human';

@NgModule({
  imports: [CommonModule],
  declarations: [
    Human
  ],
  providers: [],
  exports: [Human]
})
export class TestModule {}

如何在组件中实例化 Human 类?我都试过了:

import { TestModule } from './test.module';

import { Human } from './test.module';

但如果我这样做,new Human()我仍然会得到cannot find name Human

4

3 回答 3

3

Angular 模块和 ES6 / TypeScript / Node 模块是不同的。Angular 模块是组件、服务和指令的集合;而 ES6 模块在大多数情况下由类组成。

如果你想重用依赖于其他非 Angular 类的 NgModule,你可以将它们导出为 ES6 模块并在其他地方使用它们。有一个类似 export.ts 或 index.ts 的文件,并在其中放置以下导出语句 -

export { TestModule } from './test.module';
export { Human } from './human';

现在,当您想在某处使用 NgModule 时,您可以使用如下命令导入它 -

import { TestModule } from '../lib/export'; 
于 2017-09-08T15:04:26.193 回答
1

不应在declarationsor中提供类exports,这些类用于组件指令和管道,前提Human是存在错误。

第一个选项是Human在模块中作为值提供者(而不是类提供者)提供,因此应该手动实例化它。当类接受非 DI 参数时,首选此选项。

@NgModule({
  providers: [{ provide: Human, useValue: Human }]
})
export class TestModule {}

...

import { Human } from '...';

@Component(...)
class SomeComponent {
  constructor(@Inject(Human) Human: typeof Human) {
    this.human = new Human();
  }
}

第二种选择是制作Human组件提供者。它为每个组件实例实例化。在这种情况下TestModule是多余的。此选项通常是首选:

import { Human } from '...';

@Component({ providers: [Human], ... })
class SomeComponent {
  constructor(public human: Human) {}
}

在这两种情况下,HumanDI 令牌都应该导入到使用它的组件文件中。

于 2017-09-08T17:23:50.953 回答
0

使 Human 类可注入并在测试模块的提供程序部分中声明它。

如果您的应用程序模块(根模块)急切地加载测试模块,则在测试模块中声明的提供程序将在应用程序模块中可用,您将能够从根模块将 Human 注入您的组件中。

如果你懒加载你的测试模块,情况就不同了——它们有自己的注入器并且不与其他模块共享提供程序。

@NgModule({
  imports: [CommonModule],
  providers: [Human]
})
export class TestModule {}

我假设您正在使用路由器配置加载 TestModule:

@NgModule({
  imports: [ BrowserModule, TestModule,
    RouterModule.forRoot([
      {path: 'test', loadChildren: TestModule},
      )
  ],
    bootstrap:    [ AppComponent ]
})

在 AppComponent 中你可以注入 Human:

export class AppComponent {

  constructor(human: Human) {
    console.log(human.numOfLegs);
  }
}

确保 numOfLegs 是公开的。

于 2017-09-08T14:48:12.493 回答