AngularCLI生产构建打破字典注入

时间:2018-04-17 15:00:59

标签: angular angular-cli

我们有一个Angular应用程序,我们遵循这篇文章中的建议:

https://scotch.io/tutorials/simple-language-translation-in-angular-2-part-1

为了有一个简单的框架来根据它的部署来替换值。这一切都很好但是当我们做一个有角度的cli --prod构建时,翻译对象是空的。

基本设置是根据附带的教程,但基本上我们有一个const如下:

export const COLL1_TRANSLATIONS = {
"Key1": "Value1",
"Key2": "Value2",
"Key3": "Value3",
};

// translation token
export const TRANSLATIONS = new InjectionToken('translations');

// all translations
const dictionary = {};
dictionary["COLL1_NAME"] = COLL1_TRANSLATIONS;

// providers
export const TRANSLATION_PROVIDERS = [
    { provide: TRANSLATIONS, useValue: dictionary },
];

@Injectable()
export class TranslateService {
  public get currentLang() {
    return this._currentLang || this._defaultLang;
  }

  // inject our translations
  constructor( @Inject(TRANSLATIONS) private _translations: any) {
    console.log(_translations);
  }
}

当我们在没有--prod的情况下运行构建时,一切正常并且console.log具有填充的字典,当我们在cli构建上运行--prod时,字典为空。

这是来自几个文件的几个代码片段,以提供基本的想法,但几乎与上面的教程链接相同,正如我们不做--prod构建所提到的绝对按预期工作所以问题是为什么是 - -prod打破了字典的注入?

更新: 如果我在prod构建中添加--aot = false,那么一切都能正常工作了,有没有办法让这个工作与aot一起工作?

1 个答案:

答案 0 :(得分:1)

因为您的代码不兼容AOT,当您执行构建--prod时,默认情况下aot为true,请尝试将代码更改为

 export function tokenInjectionFunction () { 
      return new InjectionToken('translations'); 
 };

而不是

export const TRANSLATIONS = new InjectionToken('translations');

并尝试更改您的翻译提供商:

export const TRANSLATION_PROVIDERS = [
  { provide: TRANSLATIONS, useValue: dictionary },
];

要:

let dictionary = {};
dictionary["COLL1_NAME"] = COLL1_TRANSLATIONS;
export function getTransProviders() {
  return dictionary;
}

export const TRANSLATION_PROVIDERS = [
 { provide: TRANSLATIONS, useValue: getTransProviders},
];
相关问题