WebpackTranslateLoader example in the document is not accurate for Angular 6 /Rxjs 6
gwelr opened this issue ยท 8 comments
With the release of rxjs 6, the imports and creation of Observables have changed. There is no more fromPromise which has been replaced by from
This is how I updated the code to have it working:
import { TranslateLoader } from '@ngx-translate/core';
import { Observable, from } from 'rxjs';
export class WebpackTranslateLoader implements TranslateLoader {
getTranslation(lang: string): Observable<any> {
return from(System.import(`../assets/i18n/${lang}.json`));
}
}
Thanks @gwelr it works now, i get this warning any idea?
WARNING in ./src/app/loaders/webpack-translate-loader.ts
System.import() is deprecated and will be removed soon. Use import() instead.
For more info visit https://webpack.js.org/guides/code-splitting/
Same issue for me.
Just use import instead of System.import().
import { TranslateLoader } from '@ngx-translate/core';
import { Observable, from } from 'rxjs';
export class WebpackTranslateLoader implements TranslateLoader {
getTranslation(lang: string): Observable<any> {
return from(import(`../assets/i18n/${lang}.json`));
}
}
tsconfig module should be "esnext" instead of "ES2015".
see microsoft/TypeScript#24082
"module": "esnext"
@lutzleonhardt thanks, it works now with no warnings
is it safe to use "esnext" ?
Not sure about the impact. Maybe someone else know whether it's safe to use esnext instead of es2015 regarding the browser compatibility.
The way I found it to work in Angular 7:
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateUniversalLoader
}
}),
import { TranslateLoader } from '@ngx-translate/core';
import { Observable, of } from 'rxjs';
import * as contentEn from './en.json';
import * as contentRo from './ro.json';
const TRANSLATIONS = {
en: contentEn,
ro: contentRo
};
export class TranslateUniversalLoader implements TranslateLoader {
getTranslation(lang: string): Observable<any> {
return of(TRANSLATIONS[lang].default);
}
}
It looks like the returned object is added under the default key
tested this in Angular 7 and also tested dynamic change works just fine
This works fine with Angular 8 & rxjs 6.4.0
import { TranslateLoader } from '@ngx-translate/core';
import { from } from 'rxjs/index';
/** @desc Loads translations files in `src/assets/i18n/${lang}.json` */
export class WebpackTranslateLoader implements TranslateLoader {
getTranslation(lang: string) {
return from(import(`../../../../src/assets/i18n/${lang}.json`));
}
}