是否有將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';
感謝您的詳細回覆。 – Graham