forRoot方法中的角度调用函数

ism*_*tro 9 angular-module angular-cli angular angular-library

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

app.module.ts

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

...

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

environemnt.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');
Run Code Online (Sandbox Code Playgroud)

配置看起来像这样:

{
  "production": "false",
  "SENTRY_URL": "https://...@sentry.com/whatever/1"
}
Run Code Online (Sandbox Code Playgroud)

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

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

有任何想法吗??

:)

更新的解决方案:

正如Suren Srapyan所说,我的最终解决方案是在应用程序中使用函数getter.在库中,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
        }
      ]
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

:d

Sur*_*yan 7

中不支持函数调用@Decorators.替代方案,你可以获得外面的价值,@NgModule而不是使用它的价值.

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

@NgModule({
   imports: [
      BrowserModule,
      MyModule.forRoot({
      config: {
        getSentryURL: getSentryUrl
      }
    }),
    HttpClientModule,
    ...
 ]})
Run Code Online (Sandbox Code Playgroud)