一个接口不能在角度2模块中导出?
我试图接口导出一个NgModule申报出口并在编辑器(Visual Studio代码)已经收到此错误:[ts] 'MyInterface' only refers to a type, but is being used as a value here.
一个接口不能在角度2模块中导出?
下面是示例代码编辑-1:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MaterialModule } from '@angular/material';
import { MyInterface } from './my.interface';
import { MyService } from './my.service';
@NgModule({
imports: [ CommonModule, FormsModule, MaterialModule.forRoot() ],
declarations: [ MyInterface],//<- this is causing the message
exports: [ MyInterface],
providers: [ MyService ]
})
export class MyModule { }
我发现的一个解释部分in the answer to this post:“因为接口在运行时被TypeScript清除”。 我目前正在将我的应用重构为功能模块,因此我现在无法对其进行测试:只能通过从'./mypathto/my.interface'导入来使用接口吗?
您无法导出接口。只能导出:
- 其他模块
- 组件
- 指令
- 管道
NgModule
是角的概念,不应与打字稿模块相混淆。要让使用模块的第三方能够使用您的接口,您应该在模块中创建一个.d.ts
定义文件。
如果你想用你的另一NgModule内部的接口,你应该只使用:
import {InterfaceName} from 'path/to/ngmodule/to/interface';
另外,不要把声明数组中的一个接口,这只是用于管道/组件/指令。
如果你希望你的界面是一个库外部使用,你应该把它添加到您的index.ts
出口:
export {InterfaceName} from 'path/to/ngmodule/to/interface';
感谢PierreDuc为“完整答案”,澄清了很多。我发现[此文档在.d.ts上](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html)。 – Myonara
那么实际上你可以导出接口,而不是你的方式试图去做。
首先通过输入接口文件
ng g interface <interface_name>
例生成interfaces.ts文件:
export interface Auction{ $key?:string; $auctioneer:string; ... }
export interface Item{ $key?:string; condition?:string; description?:string; ...}
export interface Bid{ $key?:string; amount:number; auction:string; ...}
修改文件到您的需求后,您可以导入只有一个,全部或选择界面像这样:
import { Auction } from './interfaces';
或
import * as interfaces from './interfaces';
// then you have to call interfaces.Auction
如果你有机会知道如何在全球共享接口,让我知道这里:Angular how to share interfaces across the app
发布您的代码。导出和导入接口在这里工作得很好。 –
你想在哪里使用它?作为提供者? '我尝试在NgModule声明中导出一个接口'你是什么意思? – yurzui
查看文档https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#typescript-interfaces-aren-t-valid-tokens – yurzui