ngx-translate - check if translation file is available - javascript

How do I check if a translation file is available for the result you get from navigator.language using ngx-translate?
I want to do something like:
if( checkLanguageAvailable (navigator.language)) {
this.translate.use( navigator.language );
} else {
this.translate.use( 'en' ); //Default fall back
}

You can use the getLangs() method of ngx-translate to get a list of available languages:
#Component({ ... })
export class MyController {
constructor(private translate: TranslateService) {}
checkLanguageAvailable(lang: string): boolean {
return this.translate.getLangs().includes(lang);
}
}

u can check file exist before use it (make http.get, but this will load file...)
or use missingTranslationHandler, example:
app.module.ts
import ...
export function HttpLoaderFactory(httpClient: HttpClient) {
return new TranslateHttpLoader(httpClient, 'assets/i18n/', '.json');
}
#NgModule({
imports: [
...
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (HttpLoaderFactory),
deps: [HttpClient]
},
isolate: true,
missingTranslationHandler: [{provide: MissingTranslationHandler, useClass: TranslateHandler}]
}),
SimpleNotificationsModule.forRoot()
],
...
TranslateHandler
import {MissingTranslationHandler, MissingTranslationHandlerParams} from '#ngx-translate/core';
export class TranslateHandler implements MissingTranslationHandler {
private response: String;
handle(params: MissingTranslationHandlerParams) {
return 'some translated text'; // here u can return translation
}
}

A better solution:
this.translate.use(navigator.language.split(/-|_/)[0]).toPromise().catch(() => {
this.translate.use('en');
});

Related

How to change the language of a date picker? [duplicate]

This question already has answers here:
How to use ngx_bootstrap datepicker with frensh version
(3 answers)
Closed 13 days ago.
When I want to select a month, the month is in English. I would like to know how I can change the language to French please?
I guess I need to configure something in the core.module.ts?
#NgModule({
declarations: [],
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
AppRoutingModule,
ReferenceDataModule,
IdentityModule,
NgxsModule.forRoot(
[AppState, AuthState, ProfileState, ReferenceDataState],
{
developmentMode: !environment.production,
}
),
NgxsStoragePluginModule.forRoot({
key: ["app", "auth", "profile", "referenceData"],
storage: StorageOption.SessionStorage,
}),
BsDropdownModule.forRoot(),
ModalModule.forRoot(),
BsDatepickerModule.forRoot(),
TranslocoRootModule,
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AppHttpInterceptor,
multi: true,
},
{
provide: MODAL_CONFIG_DEFAULT_OVERRIDE,
useValue: NGX_MODAL_OPTIONS,
},
{
provide: BsDatepickerConfig,
useFactory: NGX_DATEPICKER_OPTIONS,
},
],
exports: [AppRoutingModule, TranslocoRootModule],
})
export class CoreModule {}
You can use something like this:
import { BsDatepickerModule, BsLocaleService } from 'ngx-bootstrap/datepicker';
import { defineLocale } from 'ngx-bootstrap/chronos';
import { frLocale } from 'ngx-bootstrap/locale';
defineLocale('fr', frLocale); // <--- define
export class CoreModule {
constructor(private localeService: BsLocaleService) {
this.localeService.use('fr'); // <---- set to default
}
}
you can try this solution
export class AppComponent {
constructor(
private bsLocaleService: BsLocaleService
) {
this.bsLocaleService.use('ar');
}
}
if you are trying to use it inside SharedModule
export class SharedModule {
constructor(
private bsLocaleService: BsLocaleService
) {
this.bsLocaleService.use('fr');
}
}

ngx-translate with Angular universal has problems translating parameterised value

I'm working on migrating my Angular 10 application to SSR using Angular universal and I'm facing issues with ngx-translate while translating parameterised values.
I have a translation
Bei Kauf von {quantity}
where this quantity is an attribute from our component and we normally translate it like
{{ 'LABEL' | translate: {quantity: 1} }} and we will see Bei Kauf von 1
But with SSR it's not at all translating. I see Bei Kauf von {quantity} on the page. I checked many forums and I don't see potential solutions. Any help would be much appreciated.
Here is my translate-server.loader.ts
import { join } from 'path';
import { Observable } from 'rxjs';
import { TranslateLoader } from '#ngx-translate/core';
import {
makeStateKey,
StateKey,
TransferState
} from '#angular/platform-browser';
import * as fs from 'fs';
export class TranslateServerLoader implements TranslateLoader {
constructor(
private transferState: TransferState,
private prefix: string = 'i18n',
private suffix: string = '.json'
) {}
public getTranslation(lang: string): Observable<any> {
return new Observable((observer) => {
const assets_folder = join(
process.cwd(),
'dist',
'my-app',
'browser',
'assets',
this.prefix
);
const jsonData = JSON.parse(
fs.readFileSync(`${assets_folder}/${lang}${this.suffix}`, 'utf8')
);
// Here we save the translations in the transfer-state
const key: StateKey<number> = makeStateKey<number>(
`transfer-translate-${lang}`
);
this.transferState.set(key, jsonData);
observer.next(jsonData);
observer.complete();
});
}
}
export function translateServerLoaderFactory(transferState: TransferState) {
return new TranslateServerLoader(transferState);
}
translate-browser.loader.ts
import { Observable } from 'rxjs';
import { TranslateLoader } from '#ngx-translate/core';
import {
makeStateKey,
StateKey,
TransferState
} from '#angular/platform-browser';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
import { HttpClient } from '#angular/common/http';
export class TranslateBrowserLoader implements TranslateLoader {
constructor(private http: HttpClient, private transferState: TransferState) {}
public getTranslation(lang: string): Observable<any> {
const key: StateKey<number> = makeStateKey<number>(
`transfer-translate-${lang}`
);
const data = this.transferState.get(key, null);
// First we are looking for the translations in transfer-state,
// if none found, http load as fallback
if (data) {
return new Observable((observer) => {
observer.next(data);
observer.complete();
});
} else {
return new TranslateHttpLoader(this.http).getTranslation(lang);
}
}
}
export function translateBrowserLoaderFactory(
httpClient: HttpClient,
transferState: TransferState
) {
return new TranslateBrowserLoader(httpClient, transferState);
}
app.server.module.ts
import { NgModule } from '#angular/core';
import { ServerModule, ServerTransferStateModule } from '#angular/platform-server';
import { FlexLayoutServerModule } from '#angular/flex-layout/server';
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { translateServerLoaderFactory } from './shared/loaders/translate-server.loader';
import { TransferState } from '#angular/platform-browser';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { EnvironmentService } from '~shared/services/environment.service';
#NgModule({
imports: [
AppModule,
ServerModule,
ServerTransferStateModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: translateServerLoaderFactory,
deps: [TransferState]
}
}),
FlexLayoutServerModule,
],
providers: [EnvironmentService],
bootstrap: [AppComponent],
})
export class AppServerModule {}
app.module.ts
imports: [
....,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: translateBrowserLoaderFactory,
deps: [HttpClient, TransferState]
}
}),
]
Note: It's working fine for all others which don't have any parameterised values in translations
It should be double curly brackets
Bei Kauf von {{quantity}}
wanna notice 2 more things, idk if it changed in last versions of Angular, but don't forget to register TransferState in app.module providers
providers: [
TransferState,
...
]
and for translate-server.loader.ts if you have some type errors for node.js use
/// <reference types="node" /> // add this line
import {join} from 'path';
at the top.
If it doesn't help, try to add
"types" : ["node", "express"],
to your tsconfig.json inside "compilerOptions"
It took me some time))

Initialize Guard with value

Is it possible to initialize guard with a specifig value ?
For example the current example will not work:
#Module({
imports: [
CoreModule,
],
providers: [
{
provide: AuthGuard, // while using APP_GUARD works
useFactory: (configService: ConfigService) => {
return new AuthGuard(configService.get('some_key'));
},
inject: [ConfigService],
},
],
})
While using APP_GUARD for provide will initialise the guard with config value. So it works only for global scope, but not for #UseGuards(AuthGuard)
This doesn't work because guards are not registered as providers in a module. They get directly instantiated by the framework.
You can either use dependency injection in the guard:
#Injectable()
export class MyAuthGuard {
constructor(private readonly configService: ConfigService) {
// use the configService here
}
}
and
#UseGuards(MyAuthGuard)
or instantiate the guard yourself:
#UseGuards(new AuthGuard(configService.get('some_key')))
In the special case of the AuthGuard, you can set a defaultStrategy in the PassportModule. Then you can just use #UseGuards(AuthGuard())
PassportModule.register({ defaultStrategy: 'jwt'})
or async:
PassportModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({ defaultStrategy: configService.authStrategy}),
inject: [ConfigService],
})
Let's say you want your specific guard instance to perform differently depending on some input, basically be able to configure it. There is no option to consume this config from constructor(). Factory way might look like a bit bulky solution. But you're still able to utilise static methods to achieve wanted behaviour.
Example:
#Injectable()
class SomeController {
#Get()
#UseGuard(AuthGuard) // but how to pass smth inside AuthGuard?
public async doSomething() {}
}
Solution:
// [auth.guard.ts] file
import { UnauthorizedException, Injectable } from '#nestjs/common';
import type { CanActivate, ExecutionContext } from '#nestjs/common';
import type { GuardOptions, PatchedRequest } from './auth.types';
export interface GuardOptions {
allowAnonymous?: boolean,
allowExpired?: boolean,
}
#Injectable()
export class AuthGuard
implements CanActivate {
public options: GuardOptions = {};
public canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> {
// Guard logic
return true;
}
static configure(options: GuardOptions) {
const instance = new AuthGuard;
instance.options = options;
return instance;
}
}
// [someEntity.controller.ts] file
// imports...
#Injectable()
class SomeController {
#Get()
#UseGuard(AuthGuard.configure({ allowExpired: true })) // voila
public async doSomething() {}
}
Enjoy! Glory to Ukraine!
I would try ht less verbose approach and inject ConfigService directly into the AuthGuard in such a manner:
#Module({
imports: [
CoreModule,
],
providers: [
AuthGuard,
],
exports: [
AuthGuard,
],
})
#Injectable()
export default class AuthGuard {
constructor (protected readonly config: ConfigService) {
}
/*
...
*/
}

Use fetched config in forRoot

I'm writing an angular app which uses #ngx-translate. With TranslateModule.forRoot(...) i provide a TranslateLoader:
#NgModule({
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient, ConfigService, LogService]
}
})
]
})
Also i have a ConfigService which loads an config.json utilizing APP_INITIALIZER.
The problem is, the TranslateLoader needs an url from the config. But forRoot() runs before APP_INITIALIZER which leads to ConfigService not having loaded the config and an empty url.
Is there another way to do this?
Currently i'm thinking about manually bootstrapping angular.
For anyone still looking at this, I found a way to load translations using the TranslateLoader provider after App Init. The ngx-translate lib allows you to override the current loader. So we can pass a new factory after the app has completed bootstrapping.
export function HttpLoaderFactory(handler: HttpBackend, valueAvailableAfterInit) {
const http = new HttpClient(handler);
return new TranslateHttpLoader(http, valueAvailableAfterInit, '.json');
}
export class AppModule {
constructor(
private translate: TranslateService,
private handler: HttpBackend
) {}
ngDoBootstrap() {
const valueAccessableAfterBootstrap = `I'll leave this to your use-case. For me it is an environment variable overwritten via ngOnInit in app.component`;
this.translate.currentLoader = HttpLoaderFactory(this.handler, valueAccessableAfterBootstrap); // replace loader
this.translate.reloadLang('en-US').pipe(take(1)).subscribe(); // reload translations with new loader
}
}
I think the following solution is simpler, since you don't need to reload the translations:
#NgModule({
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient, AppConfigService],
},
})
]
})
export function HttpLoaderFactory(http: HttpClient, appConfigService: AppConfigService) {
return new CustomTranslateHttpLoader(http, appConfigService, '', `?v=${environment.version}`);
}
export class CustomTranslateHttpLoader extends TranslateHttpLoader {
constructor(http: HttpClient,
private readonly appConfigService: AppConfigService,
prefix?: string,
suffix?: string) {
super(http, prefix, suffix);
}
override getTranslation(lang: string): Observable<Object> {
this.prefix = `${this.appConfigService.getConfig().apiUrl}api/translations/`;
return super.getTranslation(lang);
}
}
You can retrieve your config values after the app is initialized, as soon as getTranslation is called.
You could also resolve the translation service and make the http call to the endpoint. This only works if your services resolve the api url as well.
export class CustomTranslateHttpLoader extends TranslateLoader {
constructor(private readonly injector: Injector) {
super();
}
override getTranslation(lang: string): Observable<Object> {
const translationService = this.injector.get(TranslationsService);
return translationService.getAllTranslations(lang, environment.version)
.pipe(map(response => {
return response as Object;
}));
}
}

How to inject $templateCache into angular hybrid APP_INITIALIZER hook?

I'm new to Angular5 and TypeScript, so it's very possible it's a simple thing I'm overlooking.
I have an Angular hybrid app that uses ngUpgrade to run AngularJS and Angular5 side-by-side. I'm trying to inject $templateCache into the OnAppInit function so that I can load all the AngularJS HTML templates before the app completely initializes. I'm getting the error "Cannot find name '$templateCacheService'" as indicated below. Is my syntax wrong or is this not possible?
I "upgrade" $templateCache in upgraded-providers.ts like this:
import { InjectionToken, Directive, ElementRef, Injector } from '#angular/core';
import { UpgradeComponent } from '#angular/upgrade/static';
export const $templateCacheService = new InjectionToken<any>('$templateCacheService');
export const $templateCacheServiceProvider = {
provide: $templateCacheService,
useFactory: (i: any) => i.get('$templateCache'),
deps: ['$injector']
};
Then in app.module.ts, I try to inject it into OnAppInit:
import { NgModule, APP_INITIALIZER, Inject } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { MatCommonModule } from '#angular/material';
import { FlexLayoutModule } from '#angular/flex-layout';
import { HttpClientModule, HttpClient, HTTP_INTERCEPTORS } from '#angular/common/http';
import { downgradeInjectable, UpgradeModule, downgradeComponent } from '#angular/upgrade/static';
import { environment } from '../environments/environment';
import {
$templateCacheServiceProvider,
$templateCacheService
} from './upgraded-providers';
import { AppComponent } from './app.component';
import { GlobalVarsService } from './core/global-vars.service';
import { WinAuthInterceptor } from './core/interceptors/win-auth.interceptor';
declare var angular: any;
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatCommonModule,
FlexLayoutModule,
HttpClientModule,
UpgradeModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: WinAuthInterceptor,
multi: true
},
{
provide: APP_INITIALIZER,
useFactory: OnAppInit,
multi: true,
deps: [GlobalVarsService, HttpClient, $templateCacheService]
},
GlobalVarsService,
$templateCacheServiceProvider
]
})
export class AppModule {
constructor(private upgrade: UpgradeModule, private http: HttpClient) { }
ngDoBootstrap() {
angular.module('app').factory('globalVars', downgradeInjectable(GlobalVarsService));
this.upgrade.bootstrap(document.body, ['app'], { strictDi: true });
}
}
////// THIS NEXT LINE GETS error TS2304: Cannot find name '$templateCacheService' /////
export function OnAppInit(globalVars: GlobalVarsService, http: HttpClient, $templateCache: $templateCacheService) {
return (): Promise<any> => {
return new Promise((resolve, reject) => {
http.get(environment.apiBase + '/api/meta/data').subscribe(x => {
globalVars.MetaData = x;
globalVars.VersionNumber = globalVars.MetaData.versionNumber;
globalVars.IsDebugBuild = globalVars.MetaData.isDebugBuild;
globalVars.User = globalVars.MetaData.user;
globalVars.ApiBase = environment.apiBase;
globalVars.Templates.forEach(template => {
$templateCache.put(template.Item1, template.Item2);
});
resolve();
});
});
};
}
This is TypeScript type error, it doesn't affect how the application works (as long as compilation errors are ignored).
templateCacheService is not a valid type here, because $templateCacheService is a variable (injection token), not a type or an interface.
Only Angular class constructors are annotated with types for DI. Since factory functions are annotated with deps property, types in function signature exist only to provide type safety. If it's not needed, types can be skipped:
export function OnAppInit(
globalVars: GlobalVarsService, http: HttpClient,
$templateCache
) { ... }
Otherwise proper types should be used. $templateCache is an object with get, put, etc methods. Appropriate types are provided with AngularJS #types/angular type definitions. It will be something like:
export function OnAppInit(
globalVars: GlobalVarsService, http: HttpClient,
$templateCache: ng.ITemplateCacheService
) { ... }

Categories

Resources