added translations
This commit is contained in:
48
src/app/i18n/translate.service.ts
Normal file
48
src/app/i18n/translate.service.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Injectable, computed, inject } from '@angular/core';
|
||||
import { LanguageService } from '../services/language.service';
|
||||
import { Translations } from './translations';
|
||||
import { ru } from './ru';
|
||||
import { en } from './en';
|
||||
import { hy } from './hy';
|
||||
|
||||
const translationMap: Record<string, Translations> = { ru, en, hy };
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class TranslateService {
|
||||
private langService = inject(LanguageService);
|
||||
|
||||
readonly translations = computed<Translations>(
|
||||
() => translationMap[this.langService.currentLanguage()] ?? ru,
|
||||
);
|
||||
|
||||
/**
|
||||
* Translate a dot-separated key with optional interpolation params.
|
||||
* Usage: t('cart.phoneMoreDigits', { count: 3 }) → "Введите ещё 3 цифр"
|
||||
*/
|
||||
t(key: string, params?: Record<string, string | number>): string {
|
||||
const parts = key.split('.');
|
||||
let result: unknown = this.translations();
|
||||
|
||||
for (const part of parts) {
|
||||
if (result && typeof result === 'object') {
|
||||
result = (result as Record<string, unknown>)[part];
|
||||
} else {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof result !== 'string') {
|
||||
return key;
|
||||
}
|
||||
|
||||
if (params) {
|
||||
return result.replace(/\{\{(\w+)\}\}/g, (_, k) =>
|
||||
params[k] !== undefined ? String(params[k]) : `{{${k}}}`,
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user