2017-05-31 57 views
2

我有一個服務作爲配置文件,用於存儲我想要在我的應用程序中使用的所有組件。所有這些組件都需要從我的主要組件加載到entryComponents中。我想將服務中的組件數組加載到主要組件的裝飾器中。在Angular 4中使用裝飾器中的服務

@Injectable() // This is the service, I want to call getComponents() later on. 
export class Configuration { 
    modules = [ 
     ChartModule 
    ] 

    components = [ 
     PiechartComponent 
    ] 

    getModules(): NgModule[] { 
     return this.modules; 
    } 

    getComponents(): Component[] { 
     return this.components; 
    } 
}; 

在主要成分我想以下幾點:

@Component({ 
    selector: 'dashboard', 
    templateUrl: './dashboard.component.html', 
    styleUrls: ['./dashboard.component.css'], 
    entryComponents: Configuration.getComponents() // Here I call the service. 
}) 

請幫幫忙!

回答

0

我已經通過立刻製作桶和常量解決了這個問題。這樣我就不必將主要模塊(和其他文件)中的所有組件導入,並且可以訪問我想要執行的所有陣列和配置。

import { TestModule } from './widgets/testmodule/test.module'; 
import { TestComponent } from './widgets/testmodule/test.component'; 

因爲我想擁有所有的模塊和組件在一個獨立的配置文件,我把它放在一個桶,並不斷在同一時間。我將所有模塊和組件導入一個位置。

現在我將所有這些模塊和組件添加到數組。稍後我將在主模塊和組件的裝飾器中使用這些數組。

export const initialization: ConfigurationConfig = { 
    modules: [ 
    TestModule, 
    AnotherModule, 
    CarModule, 
    PocModule 
    ], 
    entryComponents: Array<any> = [ 
    TestComponent, 
    AnotherComponent, 
    CarComponent, 
    PocComponent 
    ]; 
} 

在我的主要模塊中,我現在可以導入這個常量與桶中的所有進口。

import * as Configuration from './configuration.barrel'; 

@Component({ 
    selector: 'df-dashboard', 
    templateUrl: './dashboard.component.html', 
    styleUrls: ['./dashboard.component.scss'], 
    entryComponents: Configuration.initialization.entryComponents 
})