Search code examples
angularngx-translatenebular

How to use ngx-translate in Akveo Nebular auth components


I'd like to add multilingual support to an Angular application that uses Nebular UI kit. I've installed and configured ngx-translate module and it loads the translations fine. However, I'm having troubles to make it work in the authentication components. I'll try to explain it with an example:

I'm using custom components that inherit the Nebular base ones. For example, my login component is declared as follows:

export class LoginComponent extends NbLoginComponent implements OnInit {

I need to inject the ngx-translate TranslateService into it, so the constructor should be something like this:

constructor(service: NbAuthService, options: {}, cd: ChangeDetectorRef, router: Router, translate: TranslateService) {
    super(service, {}, cd, router); 
}

However, I get the following error:

Can't resolve all parameters for LoginComponent in /home/felip/projects/wfront/src/app/auth/login/login.component.ts: (?, ?, [object Object], ?, [object Object])

To avoid messing with the constructors, I also tried to use Angular's Injector to access the needed service:

app.module.ts

export let AppInjector: Injector;

login.component.ts

export class LoginComponent extends NbLoginComponent implements OnInit {
  translate = AppInjector.get(TranslateService);
  /* ... */

login.component.html

<h1 id="title" class="title">{{ "AUTH.TITLE" | translate }}</h1>

This works, and I see the text in the language that I define with translate.use() in the constructor of the application main component. However, when I change the language in runtime, the translations are not updated. I'm sure it has to do with the way I've injected TranslateService, but I don't know how I could solve it.

Any suggestions? Thanks!


Solution

  • The injection error occurs because you're not using the NB_AUTH_OPTIONS injection token to resolve options. The constructor should look like

    login.component.ts

    constructor(authService: NbAuthService, @Inject(NB_AUTH_OPTIONS) options = {}, 
      cd: ChangeDetectorRef, router: Router, translate: TranslateService) {
        super(authService, options, cd, router);
    }
    

    Working example

    https://stackblitz.com/edit/nebular-dynamic-auth-api-tj5uey

    Nebular Source

    https://github.com/akveo/nebular/blob/master/src/framework/auth/components/login/login.component.ts