【问题标题】:Use a service inside a decorator in Angular 4在 Angular 4 的装饰器中使用服务
【发布时间】:2017-11-01 12:20:43
【问题描述】:

我有一个服务作为配置文件,其中存储了我想在我的应用程序中使用的所有组件。所有这些组件都需要从我的主组件加载到 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.
})

请帮忙!

【问题讨论】:

    标签: angular


    【解决方案1】:

    我已经通过一次制作一个桶和一个常量来解决这个问题。这样我就不必在主模块(和其他文件)中导入所有组件,并且我可以访问我想做的所有数组和配置。

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

    【讨论】:

      猜你喜欢
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2016-02-28
      • 1970-01-01
      • 2019-09-10
      • 2019-02-13
      • 1970-01-01
      相关资源
      最近更新 更多