Reputation: 444
I'm trying to create a pipe which using a subscribes to a list (behavior subject) on a separate service (tranlationService). Currently the value which appear is the value before the list is populated.
When debugging in the console the subscribe is called again once the list is populated but the value in the DOM doesn't update.
@Pipe({ name: 'dictionary' })
export class DictionaryPipe implements PipeTransform {
translatedValue: string = null;
constructor(private _translationService: TranslationService) {
}
translationSubscription: Subscription;
transform(value: string, defaultValue?: string): any {
this.translationSubscription = this._translationService.dictionaryItem$
.subscribe(list => {
return this.getDictionaryValue(value, defaultValue, list);
});
return this.translatedValue;
}
getDictionaryValue(key: string, defaultValue: string, list: KeyValuePair[]): any {
if (list && key) {
for (var i = 0; i < list.length; i++) {
if (list[i].key.toLowerCase().trim() == key.replace(' ', '').toLowerCase().trim()) {
if (list[i].value.length > 0)
this.translatedValue = list[i].value;
return;
}
}
}
if (defaultValue) {
this.translatedValue = defaultValue;
return;
}
this.translatedValue = ''
return this.translatedValue;
}
ngOnDestroy() {
if (this.translationSubscription) {
this.translationSubscription.unsubscribe();
}
}
}
Upvotes: 1
Views: 897
Reputation: 71911
You have to set the pure
parameter to false:
@Pipe({ name: 'dictionary', pure: false })
export class DictionaryPipe implements PipeTransform {
// ...
}
Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, as often as every keystroke or mouse-move.
With that concern in mind, implement an impure pipe with great care. An expensive, long-running pipe could destroy the user experience.
Upvotes: 3