如何将配置数据传递给NgModule,以便使用AOT编译NgModule

时间:2017-03-15 22:54:08

标签: angular-cli angular2-aot angular-module angular2-build

我有一个客户端Angular2应用程序,它将消耗需要配置数据的第三方NgModule应用程序。我需要使配置值可用作在第三方NgModule的不同区域内调用的服务的静态属性。

客户端应用的App.Module:

    export const CONFIG_DATA = new OpaqueToken('Config Data');
    export function configHelperFactory(config: MediaConfigInterface) 
    {
        ClientConfigService.ConfigModel = config;
        return ClientConfigService;
    }

    @NgModule({
        imports:[...],
        declarations:[...],
        exports:[...],
        entryComponents:[...],
        providers:[]
    })
    export class MediaModule
    {
        static forRoot(config: MediaConfigInterface): ModuleWithProviders
        {       
            return {
                ngModule: MediaModule,
                providers:
                [
                    ClientConfigService,
                    {
                        provide: CONFIG_DATA,
                        useValue: config
                    },
                    {
                        provide: ClientConfigService,
                        useFactory: configHelperFactory,
                        deps: [CONFIG_DATA]
                    }               
                ]
            };
        }
    }

第三方NgModule被导入客户端App:

    import { MediaConfigInterface} from "../models";

    export class ClientConfigService 
    {
        static ConfigModel: MediaConfigInterface;

        static BuildMediaUrl(id: string) : string
        { 
            return '';
        };      
    }

包含来自客户端应用的配置数据的第三方NgModules静态服务:

#include <stdio.h>
#include <stdlib.h>

typedef struct Base {
  int a;
  float b;
} Base;

typedef struct Derived1 {
  int a;      // This two members have the same position as in the Base
  float b;

  // adding some other members to this struct
  int otherMember;
  int otherMember2;
} Derived1;

int main()
{
  Base *bases[2];

  // Filling the array with different structs
  bases[0] = (Base*) malloc(sizeof(Base));
  bases[1] = (Base*) malloc(sizeof(Derived1));

  bases[1]->a = 5;
  Derived1 *d1 = (Derived1*) bases[1];

  if(d1->a == 5)
    printf("SUCCESS\n");

  return 0;
}

只有在客户端应用程序中的任何组件构造函数中导入ClientConfigService时,此方法才有效(我目前正在app.component.ts中导入它)。在构造函数中导入它会导致第三方NgModule中的configHelperFactory触发,并使用配置数据设置静态属性。

此方法有效,客户端应用程序使用AOT构建。问题是在任何给定组件的构造函数中在App.Module AND 导入ClientConfigService中设置配置数据有点麻烦,所以configHelperFactory会触发。

有没有办法将配置数据传递到第三方NgModule,使用配置数据填充静态服务属性,并能够使用AOT构建客户端应用程序?

0 个答案:

没有答案