2017-08-26 54 views
0

是否有將TypeScript類導入Angular模塊的推薦方法,以便該模塊中的每個組件或服務都繼承這些定義?如何將TypeScript類集中導入到Angular模塊中?

核心問題是「爲什麼導入模塊的類沒有自動導入到該模塊中的其他組件?」

我試圖導入一個類到這樣的模塊:

registration.model.ts:

export class Event { 
    id: string; 
    name: string; 
} 

registration.module.ts:

import { Event } from './registration.model'; 

我也有將它添加到模塊中的聲明中並沒有任何效果(我一知道它什麼也沒做就從聲明數組中刪除了它):

declarations: [ 
    Event, 
    ... 
] 

registration.service.ts:

getEvents(): Observable<Event[]> { 

    return this.http.get(`api/events`) 
    .map(response => response.json()); 

} 

生成此錯誤和應用程序編譯失敗:

ERROR在 C:/代碼/註冊/ SRC /應用程序/註冊/registration.service.ts (26,29):找不到名稱'Event'。

如果我直接添加進口到registration.service.ts那麼錯誤消失,一切編譯正確:

import { Event } from './registration.model'; 

我已驗證的相對路徑是正確的模塊。我可以將其更改爲模塊中的絕對路徑,並在服務中獲得相同的錯誤。

後續編輯 感謝阿德里安的迴應,我明白現在好多了。我也發現了,你可以一次從打字稿模塊導入多個類別如下:

import * as Registration from 'app/models/registration.model'; 

回答

1

這不是它的工作原理。爲了在你的應用程序的其他部分使用Event模型類,你需要在它們的每一箇中導入它。如果你使用或不使用NgModule是無關緊要的。

NgModule被Angular compiler使用,但在它到達該步驟之前,TypeScript編譯器需要處理您的代碼。

在每一個文件要使用這個需要導入它,就像你在模塊中沒有(可能的路徑可能會在每種情況下不同的):

import { Event } from './registration.model'; 

否則打字稿不會有任何瞭解事件是什麼以及從哪裏得到它。

+0

感謝您的詳細回覆。 – Graham

0

錯誤本身說找不到名稱事件

的問題是你的親戚路徑。相對路徑是不正確的


有關信息目的:

不需要提Event classdeclarations metadata property。你應該提東西declaration array當一個類時,類與@Component decorator定義做一些與Angular context意義。

由於您使用的是純打字稿類只需要導入Eventregistration.service.ts

registration.service.ts

import { Event } from './registration.model or correct relative path'; 

getEvents(): Observable<Event[]> { // Now Event[] is declared and will not issue any error. 

    return this.http.get(`api/events`) 
    .map(response => response.json()); 

} 
+0

請看我的問題的最後幾行,我知道我可以直接導入到服務。這並不能回答我的問題。 – Graham

+0

好的。那麼看起來你的相對路徑有問題。相對路徑不正確。 – micronyks

+0

我100%肯定模塊和服務都在同一個目錄中,否則當我添加導入時服務不起作用。 VS代碼沒有顯示任何錯誤與我在模塊中的導入語句。 – Graham

相關問題