Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ng2-translate on Angular 2.0.0 with Angular CLI #249

Closed
bjornharvold opened this issue Sep 29, 2016 · 23 comments
Closed

ng2-translate on Angular 2.0.0 with Angular CLI #249

bjornharvold opened this issue Sep 29, 2016 · 23 comments

Comments

@bjornharvold
Copy link

I'm submitting a Question

[ ] 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
Not working with latest version of Angular CLI 1.0.0-beta.16

  • ng2-translate version: 2.5.0
  • Angular version: 2.0.1
  • Browser: [all]
  • Language: [all]
@vincentp
Copy link

vincentp commented Oct 11, 2016

Hi, I tried to install it today.

Version:
"@angular/core": "2.0.0",
"angular-cli": "1.0.0-beta.16",
"ng2-translate": "^3.1.0",

Added the following to my module (/app/app.module.ts):

export function createTranslateLoader(http: Http) {
  return new TranslateStaticLoader(http, './', 'locale-en.json');
}

@NgModule({
  imports: [
    TranslateModule.forRoot({ 
      provide: TranslateLoader,
      useFactory: (createTranslateLoader),
      deps: [Http]
    })
  ],
  exports: [
    TranslateModule
  ]
})

And my homepage component (/app/homepage/homepage.component.ts):

import { Component, OnInit } from '@angular/core';
import { TranslateService } from 'ng2-translate/ng2-translate';

@Component({
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.sass']
})
export class HomepageComponent implements OnInit {

  constructor(translate: TranslateService) {

    translate.get('homepage.title').subscribe((res: string) => {
      console.log('DATA: ' + res);
    });    

  }

  ngOnInit() {
  }

}

My view:

<h1>{{ 'homepage.title' | translate }}</h1>

It outputs homepage.title (removing the curly brackets), doesn't pick up the translation (no error shown in the console).

@sarbogast
Copy link

@vincentp I have exactly the same thing. Did you find a solution?

@vincentp
Copy link

I didn't dig further, no solution yet

@sarbogast
Copy link

I think I found the problem. Once I moved my i18n folder under src, everything worked.

@hantsy
Copy link

hantsy commented Oct 30, 2016

I also encountered a problem when I used Angular CLI, it raised an error.

The pipe 'translate' could not be found

@SamVerschueren
Copy link
Collaborator

Please read this comment #219 (comment)

@hantsy nothing to with Angular CLI. Make sure you import TranslateModule in your shared module.

@hantsy
Copy link

hantsy commented Oct 30, 2016

@SamVerschueren Thanks for your quick response. Of course, I added TranslateModule. Just pushed my sample codes, https://github.com/hantsy/angular2-sample/, under the vanilla folder.

https://github.com/hantsy/angular2-sample/blob/master/vanilla/src/app/app.module.ts

@hantsy
Copy link

hantsy commented Oct 30, 2016

@SamVerschueren I have just tried, get lang value from Component is working.

I added the following to AppComponent, it print the desired value.

console.log('posts of lang:'+ this.translate.instant('posts'));

But I added translate pipe in to navbar component, it raised the above errors.

https://github.com/hantsy/angular2-sample/blob/master/vanilla/src/app/shared/navbar.component.html

@hantsy
Copy link

hantsy commented Oct 30, 2016

@SamVerschueren I found ng2-translate does not find the translation value of the lang key at all. When I added a MyMissingTranslationHandler, it print my formatted key.

I can see my the content from http://localhost:4200/assets/i18n/en.json, but what is wrong here.

useFactory: (http: Http) => new TranslateStaticLoader(http, './assets/i18n', '.json'),

I added a standalone module to configure TranslateModule now.

import { NgModule } from '@angular/core';
import { HttpModule, Http } from '@angular/http';
import { TranslateModule, TranslateLoader, TranslateStaticLoader, MissingTranslationHandler } from 'ng2-translate';

export class MyMissingTranslationHandler implements MissingTranslationHandler {
  handle(key: string) {
      return 'missing key: [' + key + ']';
  }
}

// class CustomLoader implements TranslateLoader {
//     getTranslation(lang: string): Observable<any> {
//         return Observable.of({"KEY": "Value"});
//     }
// }
// TranslateModule.forRoot({ provide: TranslateLoader, useClass: CustomLoader })

@NgModule({
  imports: [
    HttpModule,
    TranslateModule.forRoot({
      provide: TranslateLoader,
      useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
      deps: [Http]
    })
    ],
  exports: [TranslateModule],
  providers: [{ provide: MissingTranslationHandler, useClass: MyMissingTranslationHandler }],
})
export class AppTranslateModule { }

@ocombe
Copy link
Collaborator

ocombe commented Oct 30, 2016

if you're using html5 urls, then you shouldn't use the path './assets/i18n' but '/assets/i18n'

@hantsy
Copy link

hantsy commented Oct 30, 2016

@ocombe I have tried both, none of them is working. always printing missing key:[xxx] in codes, and translate pipe still does not work.

@SamVerschueren
Copy link
Collaborator

Have you manually checked if that file actually is present in your dist directory?

@hantsy
Copy link

hantsy commented Oct 30, 2016

It seems Angular CLI does not created a dist folder at runtime when in development env.

As I said above, I can get the translation content via URL directly, http://localhost:4200/assets/en.json, if the file is found by ng2-translate, why the translations are not found in this file.

The codes is here.

https://github.com/hantsy/angular2-sample/blob/master/vanilla

Translations files are in assets/i18n folder.

@SamVerschueren
Copy link
Collaborator

@hantsy Thanks for the code. Could you point me to the file where it tries to load a value with a certain key but can't find it?

@SamVerschueren
Copy link
Collaborator

@hantsy I also created a repository that shows how it works with angular-cli. The first commit is just a ng new initialisation, the second commit is where ng2-translate is being configured. It might help.

@hantsy
Copy link

hantsy commented Oct 31, 2016

@SamVerschueren

I was trying to load a vlaue in the AppComponent.

My config is almost like, except I use the arrow function instead of explicit function as factory.

But it does not work, unfortunately, ng2-translate does not raised helpful exception to indicate where is wrong.

@SamVerschueren
Copy link
Collaborator

Could you confirm that it does not load both of them? https://github.com/hantsy/angular2-sample/blob/master/vanilla/src/app/app.component.ts#L22-L23

@hantsy
Copy link

hantsy commented Oct 31, 2016

@SamVerschueren All printed missing key [xxxx](as my MyMissingTranslationHandler .)

@SamVerschueren
Copy link
Collaborator

@hantsy The docs state:

instant(key: string|Array, interpolateParams?: Object): string|Object: Gets the instant translated value of a key (or an array of keys). /!\ This method is synchronous and the default file loader is asynchronous. You are responsible for knowing when your translations have been loaded and it is safe to use this method. If you are not sure then you should use the get method instead.

The language file is not yet loaded when you call translate.instant in the app constructor. If you need a value in the constructor at that point in time, you should use this

this.translate.get('posts').subscribe(t => {
  console.log(t); //=> 'Posts'
});

But most of the time you can do everything with the translate pipe in your view directly. So yes it works, and no it has nothing to do with ng2-translate.


To come back to your issue regarding the translate pipe not working.

Me: Make sure you import TranslateModule in your shared module.

You: Of course, I added TranslateModule.

Yes you added TranslateModule, but not to your SharedModule. This should do it

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { TranslateModule } from 'ng2-translate';        // <- THIS

import { ShowAuthedDirective } from './show-authed.directive';
import { NavbarComponent } from './navbar.component';
import { FooterComponent } from './footer.component';


@NgModule({
  imports: [
    CommonModule,
    RouterModule
  ],
  declarations: [
    ShowAuthedDirective,
    NavbarComponent,
    FooterComponent
  ],
  exports: [
    TranslateModule,                // <- THIS
    ShowAuthedDirective,
    NavbarComponent,
    FooterComponent
  ],
})
export class SharedModule { }

@hantsy
Copy link

hantsy commented Nov 3, 2016

@SamVerschueren Defining a shared module is not a must, I checked the ng2-translate documentation.

I have read the Angular style guide. I am confused why all of other modules work well, but this module is an exception.

For the translate.instant, i hope it works like ng1 translate, always return a value synchronously.

@SamVerschueren
Copy link
Collaborator

Defining a shared module is not a must, I checked the ng2-translate documentation.

Nope it isn't, if you are not using that approach, make sure to import TranslateModule to every module where you want to use the pipe. But you do have a SharedModule so use it where it's designed for. That's how modules work and ng2-translate is no exception to this. If you don't understand that, I'd suggest reading the module section again.

For the translate.instant, i hope it works like ng1 translate, always return a value synchronously.

The docs are clear about this.

@SamVerschueren
Copy link
Collaborator

I'm closing this as the original question was answered.

@hantsy
Copy link

hantsy commented Nov 3, 2016

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants