typescript 我如何将一个类导出到模块并在带有角度的打字稿中的另一个模块中导入相同的类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43632248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:29:17  来源:igfitidea点击:

How can i export a class to module and import the same in another module in typescript with angular

angulartypescriptangular2-formsng-modules

提问by praveen

I have a class(IGeneric) which is exported to the module A and I imported that Module(A) in module B, but I could not use that exported class(IGeneric) in the module B.

我有一个IGeneric导出到模块 A的类(),我在模块 B 中导入了该模块(A),但我无法在模块 B 中使用导出的类(IGeneric)。

Note : that exported class is not a component,directive and service.it is a plain typescript class

注意:导出的类不是组件、指令和服务。它是一个普通的打字稿类

Any help will be appreciated, thanks in advance. The class which I am trying to export

任何帮助将不胜感激,提前致谢。我试图导出的类

export class IGeneric{
header : any[];
content : [{
   lable :any,
   value :any
}]
}

回答by Hearen

There is a trick to hidethe details within a module by barrel files, via which you can

有一个技巧可以隐藏模块中的细节barrel files,通过它您可以

  • just introduce the barrel file (normally named as index.ts) to that module, and
  • export everything you intend to export in that barrel file, and then
  • import the module pathwhenever you try to use the exported class/interface or components;
  • 只需将桶文件(通常命名为index.ts)引入该模块,然后
  • 导出您打算在该桶文件中导出的所有内容,然后
  • 每当您尝试使用导出的类/接口或组件时,请导入模块路径

As a follow-up, there is an another answerto elaborate what you can achieve by using barrel files.

作为后续,还有另一个答案来详细说明您可以通过使用桶文件来实现什么。

回答by Amit Chigadani

indexfile will be helpful to you if you don't want to show the entire path of your class

index如果您不想显示课程的整个路径,文件将对您有所帮助

Assume that you have a module MyModulewithin which you have IGenericclass

假设您有一个模块MyModule,其中有IGeneric

igeneric.model.ts

igeneric.model.ts

export class IGeneric{
header : any[];
content : [{
   lable :any,
   value :any
}]

Index file should be inside your Module MyModuledirectory

索引文件应该在你的模块MyModule目录中

index.ts

索引.ts

export * from 'app/MyModule/igeneric.model';

Then in your component you can import

然后在您的组件中,您可以导入

import {IGeneric} from 'app/MyModule'

回答by danimal

This looks like an ES6/Typescript module import/export issue rather than an issue for (the completely different and separate) NgModule system. If this is the case, then you simply need to importthe class you want from the file you want at the top of the .ts file, e.g.:

这看起来像是 ES6/Typescript 模块导入/导出问题,而不是(完全不同且独立的)NgModule 系统的问题。如果是这种情况,那么您只需import要从 .ts 文件顶部的文件中选择所需的类,例如:

import { IGeneric } from './relative/path/to/definition';

and then use the class as you would normally in a component/service etc

然后像通常在组件/服务等中一样使用该类

public generic: IGeneric;