2016-11-26 36 views
3

當我創建一個新的頁面組件時,我現在必須將它放在聲明中以及entryComponents數組中。爲什麼它必須在兩個地方?在聲明數組中放置組件以及entryComponents數組

如我剛剛創建了一個新的login.page.ts文件,但我要聲明這兩個聲明和entryComponents陣列(順便說一句,它不是一個entryComponent這麼說)

app.module.ts

@NgModule({ 
    declarations: [ 
    MyApp, 
    LoginPage 
    ], 
    imports: [ 
    IonicModule.forRoot(MyApp), 
    ], 
    bootstrap: [IonicApp], 
    entryComponents: [ 
    MyApp, 
    LoginPage 
    ], 
    providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}] 
}) 
export class AppModule {} 
+0

很難說什麼時候沒有代碼代碼用於聲明輸入組件以及它使用的位置。 – silentsod

回答

1

如果您的應用程序的其餘部分配置正確,則應該不需要放置entryComponent。

Angular自動將某些組件添加到條目組件。 自動添加@NgModule.bootstrap中列出的組件。 自動添加router configuration中引用的組件。 這兩個機制幾乎涵蓋了所有入口組件。

如果您的應用程序恰巧以其他方式引導或動態加載組件 類型,則必須明確將其添加到entryComponents 。

雖然將組件添加到此列表是無害的,但最好 僅添加真正入門組件的組件。不要在其他組件的模板中包含 組件。

來自:https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-when-entry-components

1

其原因entryComponents是很好的解釋in this blog entry

entryComponents節中,我們定義了僅由它的類型加載的任何組件。所有頁面組件都是這種情況,因爲這些都是通過導航控制器加載的。

聲明性加載的組件(即在另一個組件的模板中被引用)不需要包含在entryComponents陣列中。

所以,你可以看到我們有一些重複的地方,我們必須在聲明和entryComponents部分中定義頁面組件。擁有這個單獨的entryComponents部分的原因是Angular可以爲應用編譯一個包,該包僅包含應用中實際使用的組件。

我們至少可以嘗試的是避免代碼重複。 註釋中的動態代碼沒有多少自由。嘗試使用像

const myComponents = [ 
    MyComponent 
] 
const myPages = [ 
    MyApp, 
    LoginPage 
] 
@NgModule({ 
entryComponents: myComponents.concat(myPages), 
/* ... */ 
}) 

的表達將導致產生entryComponents

Error: Error encountered resolving symbol values statically. 
Function calls are not supported. 
Consider replacing the function or lambda with a reference to an exported function 

試圖使用導出函數這樣

export function getEntryComponents() { return [ /* ... */ ] } 

@NgModule({ 
entryComponents: getEntryComponents, 
/* ... */ 
}) 

結果:

Error: Error encountered resolving symbol values statically. 
Expression form not supported 

幸運的是有一個解決方案。您可以在此處使用陣列擴展運算符:

@NgModule({ 
    declarations: [ 
    ...myComponents, 
    ...myPages 
    ], 
    entryComponents: myPages 
/* ... */ 
}) 
+0

'spread operator'('... array')在編譯生產模式下的應用程序時似乎工作正常。有什麼建議麼? –