我正在尝试开发一个管道,用适当的字符串替换特定的关键字。为了使该管道具有干净的结构,我试图将关键字和字符串存储在另一个文件中,下面是代码:
import { Injectable } from '@angular/core';
import { AdvEnDictionary } from './advertiser-dict/adv-en-dictionary';
import { AdvFaDictionary } from './advertiser-dict/adv-fa-dictionary';
@Injectable()
export class AdvertiserDictionary {
constructor(
private advEnDictionary: AdvEnDictionary['words'],
private advFaDictionary: AdvFaDictionary['words']
) {}
getString(keyword:string, lang:string) {
switch(lang) {
case 'fa':
return this.advFaDictionary[keyword];
break;
case 'en':
return this.advEnDictionary[keyword];
break;
default:
return this.advFaDictionary[keyword];
}
}
}
还有管道:
import { Pipe, PipeTransform } from '@angular/core';
import { CookieService } from 'ngx-cookie';
import { AdvertiserDictionary } from '../classes/advertiser-dictionary';
import { PublisherDictionary } from '../classes/publisher-dictionary';
@Pipe({
name: 'translation'
})
export class TranslationPipe implements PipeTransform {
constructor(private cookieService: CookieService,
private advertiserDictionary: AdvertiserDictionary,
private publisherDictionary: PublisherDictionary,
) {}
transform(value: string, args?: any): any {
var [prefix, keyword] = value.split("-");
var lang = this.cookieService.get("lang");
switch(prefix.toLowerCase()) {
case 'pub':
return this.publisherDictionary.getString(
keyword.toUpperCase(),
lang
);
break;
case 'adv':
return this.advertiserDictionary.getString(
keyword.toUpperCase(),
lang
);
break;
}
}
}
在不同的情况下,我不断得到的是:
答案 0 :(得分:1)
您可以创建一个包含AdvertiserDictionary和PublisherDictionary的模块
@NgModule({
imports: [CommonModule],
declarations: [
TranslationPipe
],
providers: [AdvertiserDictionary,PublisherDictionary],
exports:[TranslationPipe]
})
export class TranslationModule {}
但是如果要使用Pipe,则需要导入TranslationModule
一般