Sarl sbeer
Sarl sbeer

Reputation: 55

recall apis that depending on lang param with ngx-translate

I'm using ngx-translate when I change the language to 'ar' it makes the dir property to 'rtl' and it works fine

the problem is that I'm using a 'lang' value from localStorage to send it with each request in headers by interceptor to get the right data from a database that's why when I change the language the API need to be recalled to send the 'lang' in headers with the changed one to get the Arabic or English data. How I can do that of course without reloading the application?

This my app.module.ts

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
...
import { AuthInterceptorProvider } from './auth.interceptor';

@NgModule({
  declarations: [...],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    UserModule,
    ...
    ,TranslateModule.forRoot({
      defaultLanguage:'en',
      loader:{
        provide:TranslateLoader, 
        useFactory:createTranslateLoader,
        deps:[HttpClient]
      }
    }),
    OrderModule,
    NgxSpinnerModule
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  providers: [AuthInterceptorProvider],
  bootstrap: [AppComponent]
})
export class AppModule { }
export function createTranslateLoader(http:HttpClient)
{
  
  return new TranslateHttpLoader(http,'./assets/i18n/','.json')
}

Can't inject the TranslateService because of circular dependency:

error>> "Circular dependency in DI detected for InjectionToken HTTP_INTERCEPTORS"

This is my interceptor

import { Injectable } from '@angular/core';
import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,
HttpErrorResponse,  HTTP_INTERCEPTORS} from '@angular/common/http';
import { Observable ,throwError} from 'rxjs';
import { UserAuthService } from './Services/user-auth.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { catchError, retry } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(
    private authService: UserAuthService,
    private spinner: NgxSpinnerService
  ) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const token = localStorage.getItem('access_token');
    const lang = localStorage.getItem('current_lang')
    if(token){
      this.spinner.show();
    request = request.clone({
      headers: request.headers.set('authorization', this.authService.Token)
     .set('lang', lang as string)
    });
    }
    setTimeout(() => {
      /** spinner ends after 5 seconds */
      this.spinner.hide();
    }, 1000);
    return next.handle(request).pipe(
      retry(1),
      catchError(
        (err)=>{
          if(err instanceof HttpErrorResponse){
            if(err.status === 405){
              this.authService.Logout();
            }
          }
          return throwError(err)
        }
      )
    )
    
  }
}
export const AuthInterceptorProvider = {
  provide: HTTP_INTERCEPTORS,
  useClass: AuthInterceptor,
  multi: true,
};

app.component.ts where I change the direction

ngOnInit(){
    let rootElement=document.getElementById("window_html")
    this.translateService.onLangChange.subscribe((param)=>{
      if(param.lang==" ar"){
        rootElement!.dir='rtl'     
        rootElement!.lang='ar'
      }else{
        rootElement!.dir='ltr'
        rootElement!.lang='en'        
      }
    })
  }

and header.component.ts where I change the language

changeCurrentLang(lang:string){
    this.translateService.use(lang);
    localStorage.setItem('current_lang', lang);    
    this.currentLang=lang;

  }

Upvotes: 0

Views: 300

Answers (0)

Related Questions