lephyrus / ngx-translate-messageformat-compiler

Advanced pluralization (and more) for ngx-translate, using standard ICU syntax which is compiled with the help of messageformat.js.
MIT License
93 stars 30 forks source link

Compiler doesn't work correctly #27

Closed alonstar closed 6 years ago

alonstar commented 6 years ago

I'm using Angular 6.0.4 + ngx-translate/core 10.0.2 + messageformat 2.0.2 + ngx-translate-messageformat-compiler 4.1.3.

Two language : en-US, zh-HK (en-US is default) My website can't show message correctly, so I tried to find out what's wrong in my project. I added log in the function

TranslateMessageFormatCompiler.prototype.compileTranslations = function (translations, lang) {      
    log("COMPILE before (" + lang + ")");   
    var result = this.messageFormat.compile(translations, lang);        
    log("COMPILE after (" + lang + ")", result);    
    return result;
};

Then I found the en-US didn't return. I don't know why lang is undefined and where it comes from.

[TranslateMessageFormatCompiler] COMPILE before (en-US)
[TranslateMessageFormatCompiler] COMPILE before (undefined)
[TranslateMessageFormatCompiler] COMPILE after (undefined) {Loading: ƒ, Language: ƒ, Menu: {…}, Field: {…}, Button: {…}, …}

So I removed the lang parameter from messageFormat.compile function.

TranslateMessageFormatCompiler.prototype.compileTranslations = function (translations, lang) {      
    log("COMPILE before (" + lang + ")");   
    var result = this.messageFormat.compile(translations);      
    log("COMPILE after (" + lang + ")", result);    
    return result;
};

And it works correctly.

[TranslateMessageFormatCompiler] COMPILE before (en-US)
[TranslateMessageFormatCompiler] COMPILE after (en-US) {Loading: ƒ, Language: ƒ, Menu: {…}, Field: {…}, Button: {…}, …}

Or add langs when new MessageFormat(['en-US', 'zh-HK']), it also works.

It looks like messageformat can't mapping the lang so it doesn't work. How could I do to resolve my problem?

Thanks.

alonstar commented 6 years ago

I write a test.

it("should return a corresponding object of compilation functions (other languages) ", () => {
  compiler = new TranslateMessageFormatCompiler();

  const obj = { month: "{month} Month{month, plural, one{} other{s}}" };

  const result = compiler.compileTranslations(obj, "en-US");

  expect(result.month({ month: 3 })).toBe("3 Months");
});

it throws error.

    TypeError: Cannot read property 'toString' of undefined
        at <Jasmine>
        at e (specs-bundle.js:575:57796)
        at e (specs-bundle.js:575:57966)
        at o.toString (specs-bundle.js:575:58153)
        at s.compile (specs-bundle.js:575:45618)
        at t.compileTranslations (specs-bundle.js:575:32138)
        at UserContext.<anonymous> (specs-bundle.js:582:8483)
        at <Jasmine>
lephyrus commented 6 years ago

Fixed by #29.