创建管道的可导入类-Angular 4

时间:2018-08-29 07:54:32

标签: javascript angular typescript pipe angular5

我正在尝试开发一个管道,用适当的字符串替换特定的关键字。为了使该管道具有干净的结构,我试图将关键字和字符串存储在另一个文件中,下面是代码:

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;
    }
  }

}

在不同的情况下,我不断得到的是:

  • 当仅在管道中添加类时,我不断收到类的“无提供者”错误
  • 当我在模块提供程序中添加该类时,我会得到该类的“无效参数”,而且我也不想在整个应用程序中使用该类,而只是希望在管道中使用它。

1 个答案:

答案 0 :(得分:1)

您可以创建一个包含AdvertiserDictionary和PublisherDictionary的模块

@NgModule({
  imports: [CommonModule], 
  declarations: [
    TranslationPipe  
  ],
  providers: [AdvertiserDictionary,PublisherDictionary], 
  exports:[TranslationPipe]  
})
export class TranslationModule {}

但是如果要使用Pipe,则需要导入TranslationModule

一般

  • 导入:您需要的所有模块
  • 在声明中:组件和管道
  • 在提供程序中:所有服务(所有@Inject)
  • 在导出中:您在模块外部使用的组件