【问题标题】:AngularCLI Production Build Breaks Dictionary InjectionAngular CLI 生产构建中断字典注入
【发布时间】:2018-04-17 15:00:59
【问题描述】:

我们有一个 Angular 应用程序,我们遵循了本教程中的建议:

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

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

基本设置是按照附加教程,但基本上我们有一个常量如下:

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 运行时,字典为空。

这是来自多个文件的几个代码 sn-ps 以提供基本概念,但与上面的教程链接几乎相同,正如所提到的,当我们不进行 --prod 构建时绝对可以正常工作,所以问题是为什么--prod 是否破坏了字典的注入?

更新: 如果我将 --aot=false 添加到 prod 构建中,那么一切都会再次正常运行,有没有办法使用 aot 进行这项工作?

【问题讨论】:

    标签: angular angular-cli


    【解决方案1】:

    因为你的代码不兼容AOT,所以当你执行ng buil --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},
    ];
    

    【讨论】:

    • 您好,感谢您的帮助,我已经尝试了您建议的更改,但是当我执行 --prod 构建时注入 TranslateService 构造函数时字典仍然为空,是否需要进行任何其他更改这与 AOT 兼容吗?
    • 我更新了答案,我希望它现在可以工作并更改 const 字典以让字典
    • 感谢您的帮助,虽然在 TranslateService 的构造函数中我不得不调用:constructor( @Inject(translationsTokenInjectionFunction) private _translations) { this._translations = this._translations(); } 但它得到了它的工作,感谢您的帮助。
    猜你喜欢
    • 2018-08-27
    • 1970-01-01
    • 2017-02-25
    • 2021-03-14
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    相关资源
    最近更新 更多