【问题标题】:Angular - Can InjectionToken be used with AOT Compilation?Angular - InjectionToken 可以与 AOT 编译一起使用吗?
【发布时间】:2018-04-08 10:07:27
【问题描述】:

在我的应用程序中,一个配置对象从窗口注入到 Angular 应用程序。为此,我按照以下思路开发了一些东西:

代码

模型代表配置

export class AppConfig {
    constructor(
        public apiKey: string,
        public username: string,
        public languageCode: string
    ) { }
}

创建一个 InjectionToken

import { InjectionToken } from '@angular/core';

import { AppConfig } from './shared';

export let APP_CONFIG = new InjectionToken<AppConfig>('appConfig');

这会在 AppModule 中提供

import { APP_CONFIG } from './app-config-export';
....
@NgModule({
    ....
    { provide: APP_CONFIG, useValue: (window as any).appConfig }
})

export class AppModule { }

最后注入到一个组件中

import { AppConfig } from '../shared';
import { APP_CONFIG} from './app-config-export';

....

export class AppComponent implements OnInit {
     constructor(
         @Inject(APP_CONFIG) private appConfig: any,
         private appService: AppService
     ) { }

     ngOnInit() {
         this.appService.initApp(this.appConfig);
     }
}

AOT 编译

这很好用,但是现在我一直在尝试使用 AOT 编译来构建应用程序。当我使用 AOT 运行应用程序时,appConfig 始终是null。我猜这与我注入可能与 AOT 不兼容的配置的方式有关。有没有办法让它与 AOT 一起工作?

我在 github https://github.com/angular/angular/issues/19154 上找到了这个帖子,但是我不明白“改用工厂”是什么意思。

  • 角度:4.4.4
  • Webpack:3.8.1

更新

我已经像这样更新了 AppModule:

import { APP_CONFIG } from './app-config-export';
....

export function appConfigFactory() {
    return (window as any).appConfig;
}

@NgModule({
    ....
    { provide: APP_CONFIG, useFactory: appConfigFactory() }
})

export class AppModule { }

解决方案

我已经像这样更新了 AppModule:

import { APP_CONFIG } from './app-config-export';
....

export function appConfigFactory() {
    return (window as any).appConfig;
}

@NgModule({
    ....
    { provide: APP_CONFIG, useFactory: appConfigFactory }
})

export class AppModule { }

我在 useFactory 回调中调用函数,而不是传递函数。

【问题讨论】:

  • 您在何时何地设置 window.appConfig 值?

标签: angular angular-aot


【解决方案1】:

@Pankaj Parkar 的解决方案几乎是正确的,但您还需要导出 useFactory 回调以允许 AoT:

import { APP_CONFIG } from './app-config-export';

export function configFactory() {
  return (window as any).appConfig;
}

@NgModule({
  providers: {
    provide: APP_CONFIG,
    useFactory: configFactory,
  }
})

否则你会遇到这个错误:

错误中的错误:静态解析符号值时遇到错误。不支持函数调用。考虑将函数或 lambda 替换为对导出函数的引用...

【讨论】:

  • 我正要写同样的东西 :) 我刚刚尝试了代码,但是配置现在是 undefined 而不是 null
  • 您在何处/何时设置window.appConfig?听起来它只是在你需要的时候不在那里。
  • 在加载 Angular 应用程序之前设置配置。我正在调试代码,当我在控制台中输入window.appConfig 时,我确实有一个值。
  • 更改`useFactory:appConfigFactory()` ==>`useFactory:appConfigFactory`
  • 大声笑在更新的问题中没有看到!是的,你必须传递那个函数引用,而不是它的返回值。
猜你喜欢
  • 2018-02-15
  • 2017-04-03
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多