forRoot方法内部的角度调用函数

问题描述 投票:8回答:1

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

app.module.ts

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

...

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

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');

配置看起来像这样:

{
  "production": "false",
  "SENTRY_URL": "https://[email protected]/whatever/1"
}

当我用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
        }
      ]
    };
  }
}

:d

angular angular-cli angular-module angular-library
1个回答
7
投票

@Decorators不支持函数调用。另外,你可以获得@NgModule之外的值,而不是使用它的值。

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

@NgModule({
   imports: [
      BrowserModule,
      MyModule.forRoot({
      config: {
        getSentryURL: getSentryUrl
      }
    }),
    HttpClientModule,
    ...
 ]})
© www.soinside.com 2019 - 2024. All rights reserved.