2017-02-19 9 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は角概念でありtypescriptですモジュールと混同すべきではありません。あなただけエクスポートすることができます。モジュールを使用する第三者がインターフェイスを使用できるようにするには、モジュールに.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

まあ実際にはインタフェースではなく、あなたがしようとしている道をエクスポートすることができますする。あなただけの1、すべてまたは選択したインタフェースをインポートすることができ、あなたのニーズに合わせてファイルを変更した後

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; ...} 

まずインターフェイスファイルの

ng g interface <interface_name>

例を入力してinterfaces.tsファイルを生成しますこのように:

import { Auction } from './interfaces'; 

または

import * as interfaces from './interfaces'; 
// then you have to call interfaces.Auction 

場合によっては、グローバルにインターフェイスを共有する方法を知っています。私にここでお知らせください:Angular how to share interfaces across the app

関連する問題