How to inject ChangeDetectorRef service into pipe
我正在尝试将ChangeDetectorRef服务注入到我的管道中,但是在启动时
应用程序,这是我的错误:没有ChangeDetectorRef的提供者!
我已经看到了我要执行的操作的几个示例(翻译管道或异步管道)。但这与我的不兼容...
这是我的烟斗:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | import {Injectable, Pipe, PipeTransform, ChangeDetectorRef, OnDestroy} from '@angular/core'; import {Subject} from 'rxjs/Subject'; import {LangChangeEvent, TranslateService} from '@ngx-translate/core'; @Injectable() @Pipe({ name: 'CollectionTranslation', pure: false }) export class CollectionPipe implements PipeTransform, OnDestroy { value: string; lastKey: string; onLangChange: Subject<LangChangeEvent>; constructor(private translate: TranslateService, private _ref: ChangeDetectorRef) { } updateValue(key: string, lang: string) { this.value = this.collectionTranslation(key, lang); this.lastKey = key; this._ref.markForCheck(); } transform(collectionParam: string) { // lang parameter is just here to execute the pipe each time the current lang is changed. // it's not used in the pipe if (this.lastKey === collectionParam) { return this.value; } this.updateValue(collectionParam, localStorage.getItem('kia.language')); if (!this.onLangChange) { this.onLangChange = this.translate.onLangChange.subscribe((event: LangChangeEvent) => { if (this.lastKey) { this.lastKey = null; // we want to make sure it doesn't return the same value until it's been updated this.updateValue(collectionParam, event.lang); } }); } return this.value; } private collectionTranslation(collectionParam: string, lang: string): string { let collection = ''; if (collectionParam === null || collectionParam === undefined) { return ''; } const coll = collectionParam.toUpperCase(); if (lang === 'fr') { collection = coll.startsWith('E') || coll.startsWith('S') ? 'ETE ' : 'HIVER '; } else { // Lang EN collection = coll.startsWith('E') || coll.startsWith('S') ? 'SUMMER ' : 'WINTER '; } collection = collection + coll.substring(coll.length - 2); return collection; } _dispose(): void { if (typeof this.onLangChange !== 'undefined') { this.onLangChange.unsubscribe(); this.onLangChange = undefined; } } ngOnDestroy(): void { this._dispose(); } } |
对我来说,因为它是核心,所以不需要将ChangeDetectorRef添加到模块中。
感谢您的帮助!
我认为您应该使用
但是,您可以将Component.ts文件粘贴到使用此管道的示例吗?您是否已在
希望会有所帮助