core
core copied to clipboard
translate.instant with empty string throws error: Parameter "key" required
I'm submitting a ...
[x] bug report => check the FAQ and search github for a similar issue or PR before submitting
[] support request => check the FAQ and search github for a similar issue before submitting
[x] feature request
Current behavior
Doing a translate.instant('')
on an empty string throws an error of Parameter "key" required
but doing the same on a white space doesn't throw an error. This is thrown by the instant() function itself
public instant(key: string | Array<string>, interpolateParams?: Object): string | any {
if(!isDefined(key) || !key.length) {
throw new Error(`Parameter "key" required`);
}
Expected/desired behavior Don't throw error on empty string, I often initialize my form elements with empty string and wish to have the translation working. Now because of this issue I need to check if it's not empty string then translate else it throws a load of errors.
Reproduction of the problem
Just put this anywhere in your code: console.log(this.translate.instant(''))
What is the expected behavior? No error in console
What is the motivation / use case for changing the behavior?
Please tell us about your environment: Windows 10, Angular 5
-
ngx-translate version: 9.1.1
-
Angular version: 5.0.0
-
Browser: all
I have the same issue. Would be perfect if the "instant" method was simply returning the same passed to it empty value (or undefined, or null, etc).
have the same error, it breaks the page and nothing is translated. on my page it happens sometimes, i guess when it loads to fast or not fast enough. although i have a check that the object is present.
The only thing I found to bypass this issue was to pass a white space, so if the translation key is incorrect then instead use a white space. Something along this
const myKey = '';
this.translate.instant(myKey || ' '); // this will use the white space since myKey is null or empty
This code avoids lots of problem, but it's too bad that this was never fixed at the source 😿
thanks, that will work but i rather stupid.... why is this issue not take care of :disappointed:
@ghiscoding
Thanks for your workaround, and it solves the same error with translate.stream where it is parsing an empty array. So a white space in array is required:
const myArray = [" "];
this.translate.stream(myArray);
QuickDirty, but it did save lots of time. Have to say that this issue is worth to be taken care. 🚶
@ocombe I'd be happy to open a pull request and change
if (!isDefined(key) || !key.length) { throw new Error(
Parameter "key" required); }
to something like
if (!isDefined(key) || !key.length) { return '' }
if this makes sense ?
there is any pull request to fix this?
Any updates on this?
One vote for this update
insane that this is not fixed yet. Wrapping the key in an array also works
const myKey = '';
this.translateService.instant([myKey]); // this will use the array and this works