在Angular 4中使用装饰器内的服务

时间:2017-05-31 15:39:44

标签: angular

我有一个服务作为配置文件,我存储了我想在我的应用程序中使用的所有组件。所有这些组件都需要从我的主要组件加载到entryComponents中。我想将服务中的组件数组加载到主组件的装饰器中。

@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.
})

请帮忙!

1 个答案:

答案 0 :(得分: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
})