13

问题是我在 forRoot 方法中调用了一个函数,如下所示:

app.module.ts

import {environment} from '../environments/environment';

...

@NgModule({
  imports: [
    BrowserModule,
    MyModule.forRoot({
      config: {
        sentryURL: environment.SENTRY_URL <-- This, calls the function
      }
    }),
    HttpClientModule,
    ...
 ]})

环境.ts

export function loadJSON(filePath) {
  const json = loadTextFileAjaxSync(filePath, 'application/json');
  return JSON.parse(json);
}

export function loadTextFileAjaxSync(filePath, mimeType) {
  const xmlhttp = new XMLHttpRequest();
  xmlhttp.open('GET', filePath, false);
  if (mimeType != null) {
    if (xmlhttp.overrideMimeType) {
      xmlhttp.overrideMimeType(mimeType);
    }
  }
  xmlhttp.send();
  if (xmlhttp.status === 200) {
    return xmlhttp.responseText;
  } else {
    return null;
  }
}

export const environment = loadJSON('/assets/config.json');

配置如下所示:

{
  "production": "false",
  "SENTRY_URL": "https://...@sentry.com/whatever/1"
}

当我使用 aot 进行构建时,它说:

src/app/app.module.ts(41,20) 中的错误:在 'AppModule' 模板编译期间出错 装饰器不支持函数调用,但在 'environment' 'environment' 调用 'loadJSON' 中调用了 'loadJSON'。

有任何想法吗??

:)

更新的解决方案:

我的最终解决方案是,在应用程序中,使用 Suren Srapyan 所说的函数获取器。在库中,forRoot 方法应如下所示:

export const OPTIONS = new InjectionToken<string>('OPTIONS');

export interface MyModuleOptions {
  config: {
    sentryURLGetter: () => string | Promise<string>;
  }
}

export function initialize(options: any) {
  console.log('sentryURL', options.config.sentryURLGetter());
  return function () {
  };
}

@NgModule({
  imports: [
    CommonModule
  ]
})
export class MyModule {
  static forRoot(options: MyModuleOptions): ModuleWithProviders {
    return {
      ngModule: MyModule,
      providers: [
        {provide: OPTIONS, useValue: options},
        {
          provide: APP_INITIALIZER,
          useFactory: initialize,
          deps: [OPTIONS],
          multi: true
        }
      ]
    };
  }
}

:D

4

1 回答 1

9

中不支持函数调用@Decorators。或者,您可以在外部获得价值@NgModule,而不是使用它的价值。

export function getSentryUrl() {
   return environment.SENTRY_URL;
}

@NgModule({
   imports: [
      BrowserModule,
      MyModule.forRoot({
      config: {
        getSentryURL: getSentryUrl
      }
    }),
    HttpClientModule,
    ...
 ]})
于 2018-01-12T12:08:18.970 回答