refactor: update to recent changes in translator

This commit is contained in:
Rainer Killinger
2021-01-13 16:47:22 +01:00
parent 456560026c
commit 3d4c476549
20 changed files with 706 additions and 330 deletions

589
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -69,10 +69,10 @@
"core-js": "2.6.5",
"deepmerge": "3.3.0",
"form-data": "2.5.0",
"moment": "2.24.0",
"moment": "^2.29.1",
"ngx-logger": "4.1.9",
"ngx-markdown": "9.1.1",
"ngx-moment": "3.4.0",
"ngx-moment": "^5.0.0",
"rxjs": "6.6.3",
"tslib": "1.14.1",
"zone.js": "0.11.2"

View File

@@ -17,9 +17,11 @@ import {SplashScreen} from '@ionic-native/splash-screen/ngx';
import {StatusBar} from '@ionic-native/status-bar/ngx';
import {Platform} from '@ionic/angular';
import {TranslateService} from '@ngx-translate/core';
import {SCLanguageCode} from '@openstapps/core';
import {NGXLogger} from 'ngx-logger';
import {ConfigProvider} from './modules/config/config.provider';
import {SettingsProvider} from './modules/settings/settings.provider';
import {ThingTranslateService} from './translation/thing-translate.service';
import {initLogger} from './_helpers/ts-logger';
/**
@@ -50,6 +52,7 @@ export class AppComponent {
* @param statusBar TODO
* @param splashScreen TODO
* @param translateService TODO
* @param thingTranslateService TODO
* @param settingsProvider TODO
* @param configProvider TODO
* @param logger An angular logger
@@ -58,6 +61,7 @@ export class AppComponent {
private readonly statusBar: StatusBar,
private readonly splashScreen: SplashScreen,
private readonly translateService: TranslateService,
private readonly thingTranslateService: ThingTranslateService,
private readonly settingsProvider: SettingsProvider,
private readonly configProvider: ConfigProvider,
private readonly logger: NGXLogger) {
@@ -71,7 +75,8 @@ export class AppComponent {
/**
* TODO
*/
initializeApp() {
async initializeApp() {
// tslint:disable-next-line: no-floating-promises
this.platform.ready()
.then(async () => {
// Okay, so the platform is ready and our plugins are available.
@@ -102,6 +107,7 @@ export class AppComponent {
try {
// set language from settings
const languageCode = (await this.settingsProvider.getValue('profile', 'language')) as string;
this.thingTranslateService.translator.language = languageCode as SCLanguageCode;
this.translateService.use(languageCode);
} catch (error) {
this.logger.warn(error);

View File

@@ -33,6 +33,7 @@ import {MenuModule} from './modules/menu/menu.module';
import {NewsModule} from './modules/news/news.module';
import {SettingsModule} from './modules/settings/settings.module';
import {StorageModule} from './modules/storage/storage.module';
import {ThingTranslateModule} from './translation/thing-translate.module';
import {fakeBackendProvider} from './_helpers/fake-backend.interceptor';
registerLocaleData(localeDe);
@@ -76,6 +77,7 @@ const providers : Provider[] = [
NewsModule,
SettingsModule,
StorageModule,
ThingTranslateModule.forRoot(),
TranslateModule.forRoot({
loader: {
deps: [HttpClient],

View File

@@ -21,6 +21,7 @@ import {IonicModule} from '@ionic/angular';
import {TranslateModule} from '@ngx-translate/core';
import {MarkdownModule} from 'ngx-markdown';
import {MomentModule} from 'ngx-moment';
import {ThingTranslateModule} from '../../translation/thing-translate.module';
import {MenuModule} from '../menu/menu.module';
import {StorageModule} from '../storage/storage.module';
import {DataFacetsProvider} from './data-facets.provider';
@@ -132,6 +133,7 @@ import {VideoListItem} from './types/video/video-list-item.component';
}),
StorageModule,
TranslateModule.forChild(),
ThingTranslateModule.forChild(),
],
providers: [
DataProvider,

View File

@@ -1,6 +1,6 @@
<stapps-simple-card [title]="'Categories'" [content]="translator.translate(item).categories()">
<stapps-simple-card [title]="'Categories'" [content]="translator.translate(item).categories">
</stapps-simple-card>
<stapps-simple-card *ngIf="item.datePublished" [title]="'Published'"
[content]="item.datePublished | amDateFormat:'ll'"></stapps-simple-card>
<stapps-simple-card [title]="'Content'" [content]="translator.translate(item).articleBody()" [isMarkdown]="true">
<stapps-simple-card [title]="'Content'" [content]="translator.translate(item).articleBody" [isMarkdown]="true">
</stapps-simple-card>

View File

@@ -1,2 +1,2 @@
<stapps-simple-card [title]="'Categories'" [content]="translator.translate(item).categories()">
<stapps-simple-card [title]="'Categories'" [content]="translator.translate(item).categories">
</stapps-simple-card>

View File

@@ -1,8 +1,8 @@
<stapps-simple-card [title]="'Categories'" [content]="translator.translate(item).categories()">
<stapps-simple-card [title]="'Categories'" [content]="translator.translate(item).categories">
</stapps-simple-card>
<ion-card *ngIf="item.characteristics">
<ion-card-header>Characteristics</ion-card-header>
<ion-card-content *ngFor="let characteristic of translator.translate(item).characteristics()">
<ion-card-content *ngFor="let characteristic of translator.translate(item).characteristics">
<p>
<img *ngIf="characteristic.image"
[src]="characteristic.image" /><span>&nbsp;{{characteristic.name}}</span>&nbsp;&nbsp;
@@ -10,7 +10,7 @@
</ion-card-content>
</ion-card>
<stapps-offers-detail *ngIf="item.offers" [offers]="item.offers"></stapps-offers-detail>
<stapps-simple-card *ngIf="item.additives" [title]="'Additives'" [content]="translator.translate(item).additives().join(', ')">
<stapps-simple-card *ngIf="item.additives" [title]="'Additives'" [content]="translator.translate(item).additives.join(', ')">
</stapps-simple-card>
<ion-card *ngIf="item.nutrition">
<ion-card-header>Average Nutrition Information</ion-card-header>

View File

@@ -1,5 +1,5 @@
<ng-container *ngIf="item.type === 'academic event'">
<stapps-simple-card *ngIf="item.categories" [title]="'Categories'" [content]="translator.translate(item).categories()">
<stapps-simple-card *ngIf="item.categories" [title]="'Categories'" [content]="translator.translate(item).categories">
</stapps-simple-card>
<stapps-simple-card *ngIf="item.catalogs" [title]="'Catalogs'" [content]="item.catalogs"></stapps-simple-card>
<stapps-simple-card *ngIf="item.performers" [title]="'Performers'" [content]="item.performers"></stapps-simple-card>

View File

@@ -1,6 +1,6 @@
<stapps-place-mensa-detail-content [item]="item" [language]="language" *ngIf="isMensaThing(item)"></stapps-place-mensa-detail-content>
<ng-container *ngIf="item.type !== 'floor'">
<stapps-simple-card *ngIf="item.type !== 'floor' && item.categories" [title]="'Categories'" [content]="translator.translate(item).categories()"></stapps-simple-card>
<stapps-simple-card *ngIf="item.type !== 'floor' && item.categories" [title]="'Categories'" [content]="translator.translate(item).categories"></stapps-simple-card>
<stapps-address-detail *ngIf="item.type !== 'floor' && item.address" [address]="item.address"></stapps-address-detail>
</ng-container>
<ng-container *ngIf="item.type !== 'building'">

View File

@@ -116,14 +116,14 @@ export class ContextMenuComponent {
getTranslatedPropertyName(property: string, onlyForType?: SCThingType): string {
return (this.translator
// tslint:disable-next-line:no-any
.translatedPropertyNames(onlyForType ? onlyForType : SCThingType.AcademicEvent) as any)[property];
.translatedPropertyNames(typeof onlyForType !== 'undefined' ? onlyForType : SCThingType.AcademicEvent) as any)[property];
}
/**
* Returns translated type of given SCThingType string
* Returns translated property value
*/
getTranslatedType(scThingType: string) {
return this.translator.translatedThingType(scThingType as SCThingType);
getTranslatedPropertyValue(onlyForType: SCThingType, field: string, key?: string): string | undefined {
return this.translator.translatedPropertyValue(onlyForType, field, key);
}
/**

View File

@@ -38,34 +38,34 @@
<ion-list class="filter-group"
*ngFor="let facet of !filterOption.compact ?
filterOption.options.slice(0, compactFilterOptionCount) : filterOption.options">
<ion-list-header class="h3">
<ion-label>
{{(facet.onlyOnType ?
getTranslatedPropertyName(facet.field, facet.onlyOnType)
: (getTranslatedPropertyName(facet.field))) | titlecase}}
{{facet.onlyOnType? ' | ' + (getTranslatedType(facet.onlyOnType) | titlecase) : ''}}
</ion-label>
</ion-list-header>
<div *ngIf="facet.buckets.length > 0">
<ion-item
*ngFor="let bucket of !facet.compact ?
facet.buckets.slice(0, compactFilterOptionCount) : facet.buckets">
<ion-label class="filter-item-label">
({{bucket.count}}) {{facet.field === 'type' ? (getTranslatedType(bucket.key) | titlecase) : bucket.key | titlecase}}
<div *ngIf="!facet.field.includes('.')">
<ion-list-header class="h3">
<ion-label>
{{(facet.onlyOnType ? getTranslatedPropertyName(facet.field, facet.onlyOnType) : (getTranslatedPropertyName(facet.field))) | titlecase}}
{{facet.onlyOnType ? ' | ' + (getTranslatedPropertyValue(facet.onlyOnType, 'type') | titlecase) : ''}}
</ion-label>
<ion-checkbox
mode="ios"
[(ngModel)]="bucket.checked"
(ngModelChange)="filterChanged()"
[value]="{field: facet.field, value: bucket.key, onlyOnType: facet.onlyOnType}">
</ion-checkbox>
</ion-item>
<ion-button fill="clear"
*ngIf="!facet.compact && facet.buckets.length > compactFilterOptionCount"
(click)="facet.compact = true">
{{'menu.context.filter.showAll' | translate}}
</ion-button>
</ion-list-header>
<div *ngIf="facet.buckets.length > 0">
<ion-item
*ngFor="let bucket of !facet.compact ?
facet.buckets.slice(0, compactFilterOptionCount) : facet.buckets">
<ion-label class="filter-item-label">
({{bucket.count}}) {{facet.field === 'type' ? (getTranslatedPropertyValue(bucket.key, 'type') | titlecase) :
getTranslatedPropertyValue(facet.onlyOnType, facet.field, bucket.key) | titlecase}}
</ion-label>
<ion-checkbox
mode="ios"
[(ngModel)]="bucket.checked"
(ngModelChange)="filterChanged()"
[value]="{field: facet.field, value: bucket.key, onlyOnType: facet.onlyOnType}">
</ion-checkbox>
</ion-item>
<ion-button fill="clear"
*ngIf="!facet.compact && facet.buckets.length > compactFilterOptionCount"
(click)="facet.compact = true">
{{'menu.context.filter.showAll' | translate}}
</ion-button>
</div>
</div>
</ion-list>
<ion-button fill="clear"

View File

@@ -1,12 +1,12 @@
<ion-card *ngIf="setting">
<ion-card-header>
<span>
{{ translatedSetting.name() | titlecase }}
<ion-icon *ngIf="compactView" name="information-circle-outline" (click)="presentAlert(translator.translate(setting).name(), translator.translate(setting).description())"></ion-icon>
{{ translatedSetting.name | titlecase }}
<ion-icon *ngIf="compactView" name="information-circle-outline" (click)="presentAlert(translator.translate(setting).name, translator.translate(setting).description)"></ion-icon>
</span>
</ion-card-header>
<ion-card-content>
<ion-note *ngIf="!compactView">{{ translatedSetting.description() }}</ion-note>
<ion-note *ngIf="!compactView">{{ translatedSetting.description }}</ion-note>
<div [ngSwitch]="setting.inputType" *ngIf="isVisible" >
<ion-item *ngSwitchCase="'number'">
@@ -31,7 +31,7 @@
<!-- else show select input -->
<ion-select *ngIf="typeOf(setting.defaultValue) !== 'boolean'" interface="popover" [(ngModel)]="setting.value" (ionChange)="settingChanged()">
<ion-select-option *ngFor="let val of setting.values, index as i" [value]="val">
<div *ngIf="typeOf(val) !== 'number'">{{ translatedSetting.values()[i] | titlecase }}</div>
<div *ngIf="typeOf(val) !== 'number'">{{ translatedSetting.values[i] | titlecase }}</div>
<div *ngIf="typeOf(val) === 'number'">{{ val }}</div>
</ion-select-option>
</ion-select>
@@ -41,7 +41,7 @@
<ion-label></ion-label>
<ion-select [(ngModel)]="setting.value" multiple="true" (ionChange)="settingChanged()">
<ion-select-option *ngFor="let val of setting.values, index as i" [value]="val">
<div *ngIf="typeOf(val) !== 'number'">{{ translatedSetting.values()[i] }}</div>
<div *ngIf="typeOf(val) !== 'number'">{{ translatedSetting.values[i] }}</div>
<div *ngIf="typeOf(val) === 'number'">{{ val }}</div>
</ion-select-option>
</ion-select>

View File

@@ -84,7 +84,8 @@ export class SettingsPageComponent {
duration: 2000,
message: this.translateService.instant('settings.resetToast.message'),
});
toast.present();
return toast.present();
}
/**
@@ -165,6 +166,7 @@ export class SettingsPageComponent {
header: this.translateService.instant('settings.resetAlert.title'),
message: this.translateService.instant('settings.resetAlert.message'),
});
alert.present();
}
}

View File

@@ -12,7 +12,7 @@
<ion-list *ngFor="let categoryKey of categoriesOrder ">
<div *ngIf="objectKeys(settingsCache).includes(categoryKey)">
<ion-item-divider>
<h5>{{ translator.translate(settingsCache[categoryKey]?.settings[objectKeys(settingsCache[categoryKey]?.settings)[0]]).categories()[0] | titlecase}}</h5>
<h5>{{ translator.translate(settingsCache[categoryKey]?.settings[objectKeys(settingsCache[categoryKey]?.settings)[0]]).categories[0] | titlecase}}</h5>
</ion-item-divider>
<stapps-settings-item *ngFor="let settingKeys of objectKeys(settingsCache[categoryKey].settings)" [setting]="settingsCache[categoryKey].settings[settingKeys]"></stapps-settings-item>
</div>

View File

@@ -0,0 +1,129 @@
/*
* Copyright (C) 2020-2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {DecimalPipe} from '@angular/common';
import {Injectable, OnDestroy, Pipe, PipeTransform} from '@angular/core';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
import {Subscription} from 'rxjs';
// tslint:disable: completed-docs
@Injectable()
@Pipe({
name: 'join',
pure: false, // required to update the value when the promise is resolved
})
export class ArrayJoinPipe implements PipeTransform {
value = '';
transform(anArray: [], separator: string): unknown {
if (typeof separator !== 'string' || separator.length <= 0) {
return this.value;
}
if (!Array.isArray(anArray)){
throw new SyntaxError(`Wrong parameter in ArrayJoinPipe. Expected a valid Array, received: ${anArray}`);
}
this.value = anArray.join(separator);
return this.value;
}
}
@Injectable()
@Pipe({
name: 'split',
pure: false, // required to update the value when the promise is resolved
})
export class StringSplitPipe implements PipeTransform {
value = Array<unknown>();
transform(aString: string, splitter: string): unknown {
if (typeof splitter !== 'string' || splitter.length <= 0) {
return this.value;
}
if (typeof aString !== 'string'){
throw new SyntaxError(`Wrong parameter in StringSplitPipe. Expected a valid String, received: ${aString}`);
}
this.value = aString.split(splitter);
return this.value;
}
}
@Injectable()
@Pipe({
name: 'numberLocalized',
pure: false, // required to update the value when the promise is resolved
})
export class NumberLocalizedPipe implements PipeTransform, OnDestroy {
decialPipe: DecimalPipe;
locale: string;
onLangChange: Subscription;
value: unknown;
constructor(private readonly translate: TranslateService) {
this.decialPipe = new DecimalPipe('de-DE');
this.locale = translate.currentLang;
}
private _dispose(): void {
if (this.onLangChange?.closed) {
this.onLangChange?.unsubscribe();
}
}
ngOnDestroy(): void {
this._dispose();
}
/**
* @param value The number to be formatted.
* @param digitsInfo Decimal representation options, specified by a string
* in the following format: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
* - `minIntegerDigits`: The minimum number of integer digits before the decimal point.
* Default is `1`.
* - `minFractionDigits`: The minimum number of digits after the decimal point.
* Default is `0`.
* - `maxFractionDigits`: The maximum number of digits after the decimal point.
* Default is `3`.
*/
transform(value: unknown, digitsInfo?: string | undefined): unknown {
this.updateValue(value, digitsInfo);
this._dispose();
if (typeof this.onLangChange === 'undefined' || this.onLangChange.closed ) {
this.onLangChange = this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
this.locale = event.lang;
this.updateValue(value, digitsInfo);
});
}
return this.value;
}
updateValue(value: unknown, digitsInfo?: string | undefined): void {
// this.value = this.locale;
this.value = this.decialPipe.transform(value, digitsInfo,this.locale);
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright (C) 2020-2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {ModuleWithProviders, NgModule, Provider} from '@angular/core';
import {ArrayJoinPipe, NumberLocalizedPipe, StringSplitPipe} from './common-string-pipes';
import {ThingTranslateDefaultParser, ThingTranslateParser} from './thing-translate.parser';
import {ThingPropertyNameTranslatePipe, ThingTranslatePipe} from './thing-translate.pipe';
import {ThingTranslateService} from './thing-translate.service';
export interface ThingTranslateModuleConfig {
parser?: Provider;
}
@NgModule({
declarations: [
ThingTranslatePipe,
ThingPropertyNameTranslatePipe,
ArrayJoinPipe,
StringSplitPipe,
NumberLocalizedPipe,
// ThingTranslatorDirective
],
exports: [
ThingTranslatePipe,
ThingPropertyNameTranslatePipe,
ArrayJoinPipe,
StringSplitPipe,
NumberLocalizedPipe,
// ThingTranslatorDirective
],
})
export class ThingTranslateModule {
/**
* Use this method in your other (non root) modules to import the directive/pipe
*/
static forChild(config: ThingTranslateModuleConfig = {}): ModuleWithProviders<ThingTranslateModule> {
return {
ngModule: ThingTranslateModule,
providers: [
config.parser ?? {provide: ThingTranslateParser, useClass: ThingTranslateDefaultParser},
ThingTranslateService,
],
};
}
/**
* Use this method in your root module to provide the TranslatorService
*/
static forRoot(config: ThingTranslateModuleConfig = {}): ModuleWithProviders<ThingTranslateModule> {
return {
ngModule: ThingTranslateModule,
providers: [
config.parser ?? {provide: ThingTranslateParser, useClass: ThingTranslateDefaultParser},
ThingTranslateService,
],
};
}
}

View File

@@ -14,11 +14,10 @@
*/
import {Injectable} from '@angular/core';
import {isDefined} from '@ngx-translate/core/lib/util';
// tslint:disable: member-ordering prefer-function-over-method completed-docs
export abstract class TranslateParser {
export abstract class ThingTranslateParser {
/**
* Gets a value from an object by composed key
* parser.getValue({ key1: { keyA: 'valueI' }}, 'key1.keyA') ==> 'valueI'
@@ -32,7 +31,7 @@ export abstract class TranslateParser {
}
@Injectable()
export class TranslateDefaultParser extends TranslateParser {
export class ThingTranslateDefaultParser extends ThingTranslateParser {
/**
* TODO
@@ -80,3 +79,8 @@ export class TranslateDefaultParser extends TranslateParser {
return property;
}
}
// tslint:disable-next-line: no-any
export function isDefined(value: any): boolean {
return typeof value !== 'undefined' && value !== null;
}

View File

@@ -15,34 +15,34 @@
import {Injectable, OnDestroy, Pipe, PipeTransform} from '@angular/core';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
import {isThing, SCThings} from '@openstapps/core';
import {isThing, SCThings, SCThingType} from '@openstapps/core';
import {Subscription} from 'rxjs';
import {ThingTranslatorService} from './thing-translator.service';
import {ThingTranslateService} from './thing-translate.service';
// tslint:disable: member-ordering prefer-function-over-method completed-docs
@Injectable()
@Pipe({
name: 'translate',
name: 'thingTranslate',
pure: false, // required to update the value when the promise is resolved
})
export class ThingTranslatePipe implements PipeTransform, OnDestroy {
value = '';
value: unknown;
lastKey?: string;
lastThing: SCThings;
onLangChange: Subscription;
constructor(private readonly translate: TranslateService,
// private readonly _ref: ChangeDetectorRef,
private readonly thingTranslate: ThingTranslatorService) {
private readonly thingTranslate: ThingTranslateService) {
}
updateValue(key: string, thing: SCThings): void {
this.value = String(this.thingTranslate.get(thing, key));
this.value = this.thingTranslate.get(thing, key);
}
transform(query: string, thing: SCThings): string {
transform(query: string, thing: SCThings): unknown {
if (typeof query !== 'string' || query.length <= 0) {
return query;
}
@@ -51,20 +51,16 @@ export class ThingTranslatePipe implements PipeTransform, OnDestroy {
throw new SyntaxError(`Wrong parameter in ThingTranslatePipe. Expected a valid SCThing, received: ${thing}`);
}
// store the query, in case it changes
this.lastKey = query;
// store the params, in case they change
this.lastKey = query;
this.lastThing = thing;
// set the value
this.updateValue(query, thing);
// if there is a subscription to onLangChange, clean it
this._dispose();
// subscribe to onLangChange event, in case the language changes
if (typeof this.onLangChange === 'undefined' || this.onLangChange.closed ) {
if (this.onLangChange?.closed ?? true) {
this.onLangChange = this.translate.onLangChange.subscribe((_event: LangChangeEvent) => {
if (typeof this.lastKey === 'string') {
this.lastKey = undefined; // we want to make sure it doesn't return the same value until it's been updated
@@ -89,3 +85,68 @@ export class ThingTranslatePipe implements PipeTransform, OnDestroy {
this._dispose();
}
}
@Injectable()
@Pipe({
name: 'propertyNameTranslate',
pure: false, // required to update the value when the promise is resolved
})
export class ThingPropertyNameTranslatePipe implements PipeTransform, OnDestroy {
value: unknown;
lastKey?: string;
lastType: string;
onLangChange: Subscription;
constructor(private readonly translate: TranslateService,
// private readonly _ref: ChangeDetectorRef,
private readonly thingTranslate: ThingTranslateService) {
}
updateValue(key: string, type: string): void {
this.value = this.thingTranslate.getPropertyName(type as SCThingType, key);
}
transform(query: string, thingOrType: SCThings | string): unknown {
if (typeof query !== 'string' || query.length <= 0) {
return query;
}
if (!isThing(thingOrType) && typeof thingOrType !== 'string'){
throw new SyntaxError(`Wrong parameter in ThingTranslatePipe. Expected a valid SCThing or String, received: ${thingOrType}`);
}
// store the params, in case they change
this.lastKey = query;
this.lastType= typeof thingOrType === 'string' ? thingOrType : thingOrType.type;
this.updateValue(query, this.lastType);
// if there is a subscription to onLangChange, clean it
this._dispose();
if (this.onLangChange?.closed ?? true) {
this.onLangChange = this.translate.onLangChange.subscribe((_event: LangChangeEvent) => {
if (typeof this.lastKey === 'string') {
this.lastKey = undefined; // we want to make sure it doesn't return the same value until it's been updated
this.updateValue(query, this.lastType);
}
});
}
return this.value;
}
/**
* Clean any existing subscription to change events
*/
private _dispose(): void {
if (this.onLangChange?.closed) {
this.onLangChange?.unsubscribe();
}
}
ngOnDestroy(): void {
this._dispose();
}
}

View File

@@ -15,10 +15,9 @@
import {Injectable, OnDestroy} from '@angular/core';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
import {isDefined} from '@ngx-translate/core/lib/util';
import {SCLanguage, SCThings, SCThingTranslator, SCTranslations} from '@openstapps/core';
import {SCLanguage, SCThings, SCThingTranslator, SCThingType, SCTranslations} from '@openstapps/core';
import {Subscription} from 'rxjs';
import {TranslateParser} from './thing-translator.parser';
import {isDefined, ThingTranslateParser} from './thing-translate.parser';
// export const DEFAULT_LANGUAGE = new InjectionToken<string>('DEFAULT_LANGUAGE');
@@ -27,7 +26,7 @@ import {TranslateParser} from './thing-translator.parser';
@Injectable({
providedIn: 'root',
})
export class ThingTranslatorService implements OnDestroy {
export class ThingTranslateService implements OnDestroy {
onLangChange: Subscription;
translator: SCThingTranslator;
@@ -39,10 +38,9 @@ export class ThingTranslatorService implements OnDestroy {
* @param language TODO
*/
constructor(private readonly translateService: TranslateService,
public parser: TranslateParser,
language?: keyof SCTranslations<SCLanguage>) {
public parser: ThingTranslateParser){
this.translator = new SCThingTranslator(language ?? this.translateService.currentLang as keyof SCTranslations<SCLanguage>);
this.translator = new SCThingTranslator('de' ?? this.translateService.currentLang as keyof SCTranslations<SCLanguage>);
/** set the default language from configuration */
this.onLangChange = this.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
@@ -63,15 +61,34 @@ export class ThingTranslatorService implements OnDestroy {
* Gets the translated value of a key (or an array of keys)
* @returns the translated key, or an object of translated keys
*/
public get(thing: SCThings, keyPath: string | string[]): string | number | boolean {
public get(thing: SCThings, keyPath: string | string[]): string | number | boolean | object {
if (!isDefined(keyPath) || keyPath.length === 0) {
throw new Error(`Parameter "key" required`);
throw new Error(`Parameter "keyPath" required`);
}
if (keyPath instanceof Array) {
return this.getParsedResult(thing, keyPath.join('.'));
return this.getParsedResult(this.translator.translate(thing), keyPath.join('.'));
}
return this.getParsedResult(thing, keyPath);
return this.getParsedResult(this.translator.translate(thing), keyPath);
}
/**
* Gets the translated value of a key (or an array of keys)
* @returns the translated key, or an object of translated keys
*/
public getPropertyName(type: SCThingType, keyPath: string | string[]): string {
const translatedPropertyNames = this.translator.translatedPropertyNames(type);
if (!isDefined(translatedPropertyNames)) {
throw new Error(`Parameter "type" is an invalid SCThingType`);
}
if (!isDefined(keyPath) || keyPath.length === 0) {
throw new Error(`Parameter "keyPath" required`);
}
if (keyPath instanceof Array) {
return this.getParsedResult(translatedPropertyNames!, keyPath.join('.'));
}
return this.getParsedResult(translatedPropertyNames!, keyPath);
}
// tslint:disable-next-line: completed-docs