Core: How to setup ng2-translate to Angular2+WebPack starter kit?

Created on 12 May 2016  路  14Comments  路  Source: ngx-translate/core

How to setup ng2-translate to Angular2+WebPack starter kit (https://github.com/AngularClass/angular2-webpack-starter) ?

Could you provide all steps?

questiosupport

Most helpful comment

@maxkarpovets @dvulanov I don't use the starter kit but steps are the same.
If you have the latest version of the kit you can avoid the step 2.

  1. import in your vendors file import 'ng2-translate';
  2. You need to copy the i18n json files to assets folder using webpack, I use CopyWebpackPlugin
new CopyWebpackPlugin([
    {
        from: helpers.root('src', 'public', 'i18n'), // replace with your folder
        to: 'assets/i18n'
   }
])

All 14 comments

I would like a bit of help with this too. When I try and create the static loader inside app/index.ts:

import {TRANSLATE_PROVIDERS,
  TranslateService,
  TranslateLoader,
  TranslateStaticLoader} from 'ng2-translate/ng2-translate';
import {provide} from '@angular/core';
import {Http} from '@angular/http';


// Application wide providers
export const APP_PROVIDERS = [
  AppState,
  provide(TranslateLoader, {
    useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
    deps: [Http]
  }),
  TRANSLATE_PROVIDERS,
  TranslateService
];

it doesn't init TranslateLoader properly. I get this error in the console:

zone.js:101 GET http://localhost:3000/i18n/en.json 404 (Not Found)scheduleTask @

it ignores the 'assets/i18n' configuration and I'm guessing the entire provider initialization.

If I simply move my i18n directory to the top level, things work fine.

@maxkarpovets @dvulanov I don't use the starter kit but steps are the same.
If you have the latest version of the kit you can avoid the step 2.

  1. import in your vendors file import 'ng2-translate';
  2. You need to copy the i18n json files to assets folder using webpack, I use CopyWebpackPlugin
new CopyWebpackPlugin([
    {
        from: helpers.root('src', 'public', 'i18n'), // replace with your folder
        to: 'assets/i18n'
   }
])

Hello everybody, i need your help: @maxkarpovets @dvulanov @sliker @ocombe

I try to prepare a small example, that you can see on: https://github.com/juliovg/ng2-translate

I don't know what is wrong, can you help me?
My error is something like:
VM12832:77 TypeError: Cannot read property 'annotations' of undefined鈥╝t ReflectionCapabilities.annotations (eval at (vendor.js:237)
Really thanks

From my original query @sliker noted that you have to ensure your ./i18n is copied into the asset folder, but webpack starter kit already ensures that everything in assets is copied over to dist build.

https://github.com/ocombe/ng2-translate/issues/122 addressed the issue. Remove TRANSLATE_PROVIDERS from the bootstrap or it will override with a default loader.

Simply removing this ensures that the translate files are sources properly.

Hi @dvulanov I don't understand
i leave my main.ts like this:

import {Http, HTTP_PROVIDERS}               from '@angular/http';
import {Component, Injectable, provide}     from '@angular/core';
import {TranslateService,
        TranslatePipe, TranslateLoader,
        TranslateStaticLoader}              from 'ng2-translate/ng2-translate';
import {bootstrap}                          from '@angular/platform-browser-dynamic';

bootstrap(AppComponent, [
    HTTP_PROVIDERS,
    provide(TranslateLoader, {
        useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
        deps: [Http]
    }),
    TranslateService
]);

@Component({
    selector: 'app',
    template: `
        <div>{{ 'HELLO' | translate:{value: param} }}</div>
    `,
    pipes: [TranslatePipe]
})
export class AppComponent {
    param: string = "world";

    constructor(translate: TranslateService) {
        var userLang = navigator.language.split('-')[0]; // use navigator lang if available
        userLang = /(fr|en)/gi.test(userLang) ? userLang : 'en';

        // this language will be used as a fallback when a translation isn't found in the current language
        translate.setDefaultLang('en');

        // the lang to use, if the lang isn't available, it will use the current loader to get them
        translate.use(userLang);
    }
}

but i don't understand why i should delete TRANSLATE_PROVIDERS ?
I updeted my repository, can you send the solution ?

really thanks

@juliovg

I'm not sure why you need to remove TRANSLATE_PROVIDERS past the explanation that #122 gives. But it worked for me. Are you still having issues? Your setup looks fine to me. Although, personally I haven't tested my setup using params.

TRANSLATE_PROVIDERS is just a preset for a default configuration, but if you use a different path for the static loader, then you need to use the full bootstrap config instead of TRANSLATE_PROVIDERS.

I hope that answer your questions !

@ocombe I have pretty much follow every step and spend 2 days trying to figure out an issue I have. steps I followed are:

  • npm installed ng2-translate
  • import ng2-translate (vendors.ts)
  • TRANSLATE_PROVIDERS (added to APPLICATION_PROVIDERS)
  • provide(TranslateLoader, {
    useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
    deps: [Http]
    }),
    TranslateService (added to bootstrap function)
  • TranslatePipe (added to APPLICATION_PIPES)
  • /i18/en.json - es.json

My issue is that the content type for the requested .json file with the translations is set to:

Content-Type:text/html; charset=UTF-8

I'm building a MEAN app with https://github.com/datatypevoid/vulgar which is based on A2 & Webpack startkit. Express is set to be serving static files in asset directory as:

app.use(express.static(__dirname + '/dist'));

i18 directory is succesfully copied into dist/

please help me!!

Nevermind, must have been too tired and just found out it was a typo in my folder named i18 missing the "n"..

@sliker Thank you so much for your help. It took me so much time to find a solution to the problem.

@dvulanov It only works when it is on the top level for me too.

"EXCEPTION: Response with status: 404 Not Found for URL:
http://localhost/[mywebsitename]/assets/i18n/fr.json"

It doesnt insert the [distFolderName] between [mywebsitename] and "assets/i18n/fr.json"

In my app.module.ts
{ provide: TranslateLoader, useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'), deps: [Http] },

I looked at #122 too, didnt help. I have used the CopyPlugin as suggested by @sliker and it does copy all the files to the distribution folder. Problem is using the public path to point to the dest folder.

This is my app.module.ts

import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpModule, Http } from '@angular/http';

export function HttpLoaderFactory(http: Http) {
    return new TranslateHttpLoader(http, "i18n/", ".json");
}

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        HomeComponent
    ],
    imports: [
        UniversalModule, FormsModule, TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [Http]
            }
          }),// Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ]
})
export class AppModule {}

imported Translate service in my ts file and rest of the code:


    constructor(private translate: TranslateService) {
        translate.addLangs(['en', 'esp']);
        translate.setDefaultLang('en');

        let browserLang: string = translate.getBrowserLang();
        translate.use(browserLang.match(/en|esp/) ? browserLang : 'en');

coming to my template

<a>{{'Translater' | translate}}</a>

    <select #langSelect (change)="translate.use(langSelect.value)">
        <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option>
    </select>

And i18n folder contains en.json fr.json files.

"EXCEPTION: Response with status: 404 Not Found for URL:

What was my mistake ?
FYI: i installed only ngx-translate

Update and add i18n to .angular-cli.json:
e.g.
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico",
"i18n"
],

Was this page helpful?
0 / 5 - 0 ratings

Related issues

IterationCorp picture IterationCorp  路  3Comments

jellene4eva picture jellene4eva  路  3Comments

chris31389 picture chris31389  路  3Comments

madoublet picture madoublet  路  3Comments

rbaumi picture rbaumi  路  4Comments