ngx-translate / core

The internationalization (i18n) library for Angular
MIT License
4.53k stars 578 forks source link

ngx-translate not working with interceptor in Ionic Capacitor app #1471

Open kumaran-IV0IV opened 9 months ago

kumaran-IV0IV commented 9 months ago

I'm facing an issue with ngx-translate while integrating it with an interceptor in my Ionic Capacitor application. When attempting to access the translate service within the interceptor, I facing the following error:

Screenshot 2024-02-26 114741

My project specs
Angular CLI: 16.2.5

Node: 18.19.0

Package Manager: npm 10.2.3

OS: win32 x64

Angular: 16.2.8

... animations, cdk, common, compiler, compiler-cli, core, forms

... language-service, material, platform-browser

... platform-browser-dynamic, router

Package Version

---------------------------------------------------------

@angular-devkit/architect 0.1602.5

@angular-devkit/build-angular 16.2.5

@angular-devkit/core 16.2.5

@angular-devkit/schematics 16.2.5

@angular/cli 16.2.5

@angular/google-maps 16.2.9

@schematics/angular 16.2.5

rxjs 7.8.1

typescript 5.0.4

zone.js 0.14.0

` my app.module.ts


import {CUSTOM_ELEMENTS_SCHEMA, NgModule} from '@angular/core';
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {TranslateService} from "@ngx-translate/core";

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  declarations: [AppComponent],
  imports: [

    AppRoutingModule,
    HttpClientModule,

    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (HttpLoaderFactory),
        deps: [HttpClient]
      }
    }),
  ],
  providers: [
    {provide: HTTP_INTERCEPTORS, useClass: InterService, multi: true},
    {
      provide: RouteReuseStrategy,
      useClass: IonicRouteStrategy,
      deps: [TranslateService]
    },

    ]
}

my interceptor

inter.service.ts

    // http-interceptor.service.ts
import {Injectable} from '@angular/core';
import {Device} from "@ionic-native/device/ngx";
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent,
} from '@angular/common/http';
import {Observable} from 'rxjs';
import {GlobalService} from "./global.service";
import {TranslateService} from "@ngx-translate/core";

@Injectable()
export class InterService implements HttpInterceptor {

  loginToken: any;

  constructor(private device: Device,
              private global: GlobalService,
              private translate: TranslateService) {

    this.global.getItem("LOGINTOKEN").then(data => {
      this.loginToken = data;
    });

  }

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const modifiedReq = req.clone({
        setHeaders: {
          'Content-Type': 'application/json',
          'DEVICE_DATE': new Date().toISOString(),
          'DEVICE_ID': this.device.uuid,
          'Accept-Language': this.translate.currentLang,
          'Access-Control-Allow-Origin': '*'
        },
      });

    console.log('Headers before request:', req.headers.keys());
    // Pass the modified request to the next handler
    return next.handle(modifiedReq);
  }
}

app.component.ts

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

    register();

    @Component({
      selector: 'app-root',
      templateUrl: 'app.component.html',
      styleUrls: ['app.component.scss'],
    })
    export class AppComponent implements OnInit {
      constructor(private translate: TranslateService,
                  ) {
        this.initTranslate();
      }

      async ngOnInit() {
      }

      initTranslate() {
        this.storage.get('LANG').then(data => {
          if (!data) {
            this.translate.setDefaultLang('en');
            this.translate.use('en');
            this.storage.set('LANG', 'en');
            this.rest.selectedLang = 'Eng';
          } else {
            this.translate.setDefaultLang(data);
            this.translate.use(data);

          }
        });
      }
    }`

I think there might be an issue with how the TranslateService is being injected or accessed within the interceptor, but I'm not sure.