libs/ngx-pfe/util/i18n-from-state/pipe/pfe-i18n-from-state.pipe.ts
| Name | pfeI18nFromState |
No results matching.
Methods |
| updateValue | ||||||||||||
updateValue(key: string, interpolateParams?: Record
|
||||||||||||
|
Overrides the original updateValue, which had the onTranslate inline.
Parameters :
Returns :
void
|
import { PFE_LOGGER, PfeBusinessService } from '@allianz/ngx-pfe';
import { ChangeDetectorRef, inject, Pipe, PipeTransform } from '@angular/core';
import { StrictTranslation, TranslatePipe, TranslateService } from '@ngx-translate/core';
import { isObservable } from 'rxjs';
import { PfeI18nFromStateHandler, REPLACEMENT_SEPARATOR } from '../pfe-i18n-from-state-handler';
@Pipe({
name: 'pfeI18nFromState',
pure: false, // required to update the value when the promise is resolved
standalone: false,
})
export class PfeI18nFromStatePipe extends TranslatePipe implements PipeTransform {
private pfeI18nFromStateHandler: PfeI18nFromStateHandler;
private translateService: TranslateService;
private changeDetectorRef: ChangeDetectorRef;
constructor() {
const translateService = inject(TranslateService);
const changeDetectorRef = inject(ChangeDetectorRef);
super();
const pfeBusinessService = inject(PfeBusinessService);
const logger = inject(PFE_LOGGER);
this.pfeI18nFromStateHandler = new PfeI18nFromStateHandler(pfeBusinessService, translateService, logger);
this.translateService = translateService;
this.changeDetectorRef = changeDetectorRef;
}
private key!: string;
/**
* Called by the original TranslatePipe when a translation values changes
*/
private onTranslation(res: StrictTranslation) {
this['value'] = res !== undefined ? res : this.key;
this.lastKey = this.key;
this.pfeI18nFromStateHandler.initializeAndSubscribe(this.key, (translatedText: string) => this.renderText(translatedText));
}
/**
* Called by PfeI18nFromStateHandler when the key is changed/translated or when one of the used state values from
* the expression changes.
*/
private async renderText(translatedText: string): Promise<void> {
let result = '';
for (const textChunk of translatedText.split(REPLACEMENT_SEPARATOR)) {
const finalText = await this.pfeI18nFromStateHandler.getFinalText(textChunk);
result = result + finalText;
}
this['value'] = result ? await this.translateService.get(result).toPromise() : '';
this.changeDetectorRef.markForCheck();
}
/**
* Overrides the original updateValue, which had the onTranslate inline.
*/
// eslint-disable-next-line no-restricted-syntax
updateValue(key: string, interpolateParams?: Record<string, unknown>, translations?: unknown): void {
this.key = key;
if (translations) {
const res = this.translateService.getParsedResult(key, interpolateParams);
if (isObservable(res)) {
res.subscribe((result: StrictTranslation) => {
this.onTranslation(result);
});
} else {
this.onTranslation(res);
}
}
this.translateService.get(key, interpolateParams).subscribe((result) => {
this.onTranslation(result);
});
}
}