Issue
this is my custom pipe
import { Pipe, PipeTransform } from '@angular/core';
import { LanguageFile } from './files/language';
@Pipe({
name: 'lang'
})
export class NgxTogetherLanguageTranslatorPipe implements PipeTransform {
language: any;
constructor() {
this.language = LanguageFile.language;
}
transform(value: string, falg = "fa"): string {
if (typeof (value) != typeof ('x1'))
return value;
let key = value ? value.toLowerCase() : value;
if (sessionStorage.getItem('languageFlag'))
falg = sessionStorage.getItem('languageFlag') || falg;
if (window && falg == "fa")
return this.language[key] ? (this.language[key].fa || value) : value;
else
return this.language[key] ? (this.language[key].en || value) : value;
}
}
is it possible i override another file or variable on LanguageFile when i'm providing it into a module?
i have created a library for this pipe and i want to use it in multiple project, my challenge is want to use different files this is the file content :
export class LanguageFile {
public static language = {
"cancel": { "fa": "لغو", "en": "Cancel" },
"ok": { "fa": "تایید", "en": "OK" },
}
}
Solution
yes, it's possible, you can use InjectionToken to achieve this.
Basically, you can create token
const LANGUAGE = new InjectionToken<string>('language');
and on parent level provide value you want to use in your pipe (parent - module or component with pipe inside)
If you know value you want to use in compilation time, you can use something like
{providers: [{provide: LANGUAGE, useValue: LanguageFile.language}]
And if you need to use some logic in runtime, you can use useFactory instead
Finally, just inject value in your pipe like
constructor(@Inject(LANGUAGE) private language: string) {}
Answered By - Alex Voloshyn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.