2017-07-18 34 views
0

例如,我有一個類A.ts如何導入所有類在一個文件中,並利用它們從那裏打字稿

export class A(){ 
    public constructor() {} 
    public method() : string { 
     return "hello from A"; 
    } 
} 

和類B.ts

export class B(){ 
    public constructor() {} 

    public method() : string { 
     return "hello from B"; 
    } 

    public static methodStatic() : string { 
     return "hello from static B"; 
    } 
} 

那麼我想將它們全部導入到一個文件中Headers.ts

imports {A} from "../A_path"; 
imports * as b from "../B_path"; 

//Or just to export it? Make it public. 
export * from "../A_path"; 
export * from "../B_path"; 

Headers.ts將只包含imports/exports,沒有類實現或任何其他代碼。 然後我的問題:我想在app.ts稱他們在Headers.ts文件中使用AB類。

import * as headers from './HEADERS_path'; 
headers.A.method(); 
headers.B.method(); 

該怎麼做?

回答

0

OK我找到了解決辦法: 文件Headers.ts在我只需要出口類:

export {A} from "../A_path"; 
export {B} from "../B_path"; 

,然後使用類,我需要進口Headers.tsapp.ts文件:

import * as headers from './HEADERS_path'; 

然後我要讓一個實例的B類,並很容易地調用它的方法:

let bInstance : headers.B = new headers.B(); 
//concrete method 
bInstance.method(); 
//output will be what is expected: *"hello from B"* 

//static method 
headers.B.methodStatic(); 
//output will be what is expected: *"hello from static B"* 
0

你必須所有類導出Headers.ts

export {A} from "../A_path"; 
export {B} from "../B_path"; 

如果你有多個班A_path例如,你可以這樣做:

export * from "../A_path";

請注意,您不能使用export * fromdefault出口。

您可以在MDN上閱讀更多關於導入/導出的內容。

相關問題