【问题标题】:Angular call function inside forRoot methodforRoot 方法中的 Angular 调用函数
【发布时间】:2019-03-20 10:25: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,
    ...
 ]})

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://...@sentry.com/whatever/1"
}

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

src/app/app.module.ts(41,20) 中的错误:“AppModule”模板编译期间出错 装饰器不支持函数调用,但在“环境”中调用了“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

【问题讨论】:

标签: angular angular-cli angular-module angular-library


【解决方案1】:

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

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

@NgModule({
   imports: [
      BrowserModule,
      MyModule.forRoot({
      config: {
        getSentryURL: getSentryUrl
      }
    }),
    HttpClientModule,
    ...
 ]})

【讨论】:

  • 我已经更新了。也试试这个方法。在forRoot 调用中
猜你喜欢
  • 2018-09-18
  • 2019-03-10
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 2015-12-07
  • 1970-01-01
  • 2023-02-24
相关资源
最近更新 更多