2017-02-19 153 views
6

我試圖接口導出一個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'導入來使用接口嗎?

+0

發佈您的代碼。導出和導入接口在這裏工作得很好。 –

+1

你想在哪裏使用它?作爲提供者? '我嘗試在NgModule聲明中導出一個接口'你是什麼意思? – yurzui

+1

查看文檔https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#typescript-interfaces-aren-t-valid-tokens – yurzui

回答

13

您無法導出接口。只能導出:

  1. 其他模塊
  2. 組件
  3. 指令
  4. 管道

NgModule是角的概念,不應與打字稿模塊相混淆。要讓使用模塊的第三方能夠使用您的接口,您應該在模塊中創建一個.d.ts定義文件。

如果你想用你的另一NgModule內部的接口,你應該只使用:

import {InterfaceName} from 'path/to/ngmodule/to/interface'; 

另外,不要把聲明數組中的一個接口,這只是用於管道/組件/指令。

如果你希望你的界面是一個庫外部使用,你應該把它添加到您的index.ts出口:

export {InterfaceName} from 'path/to/ngmodule/to/interface'; 
+0

感謝PierreDuc爲「完整答案」,澄清了很多。我發現[此文檔在.d.ts上](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html)。 – Myonara

3

那麼實際上你可以導出接口,而不是你的方式試圖去做。

首先通過輸入接口文件

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