Angular2 dynamic pipe

2019-07-22 14:26发布

问题:

I'm using a pipe to internationalize my app:

import {Pipe, PipeTransform} from '@angular/core';
import {I18nService} from './i18n.service';

@Pipe({
  name: 'i18n'
})
export class I18nPipe implements PipeTransform {

  constructor(private i18nService: I18nService) {
  }

  transform(value: any, args?: any): any {
    return this.i18nService.get(value);
  }

}

This pipe calls a service:

import {Injectable} from '@angular/core';

const i18n = {
  en: {
    hello: 'Hello'
  },
  fr: {
    hello: 'Salut'
  }
};

@Injectable()
export class I18nService {

  language: string = 'en';

  constructor() {
  }

  get(key: string) {
    let languageObject = i18n[this.language];
    return languageObject[key];
  }

}

In a component I use it like this:

<div (click)="switchLanguage()">{{'hello' | i18n}}</div>

switchLanguage() {
  this.i18nService.language = 'en' ? 'en' : 'fr';
}

However, even though the service language value has been changed, the pipe result is not reevaluated. I need to navigate to any other route and come back to see this change taken into account.

I tried ApplicationRef.tick() and NgZone.run(callback) without any luck.

Any idea on how to reevaluate every pipes of the app, without navigating to another route or reloading the page ?

Thanks

回答1:

Your pipe should be marked as not pure, because the result of its transformation for a given input can change even though the input hasn't changed.

See the documentation for explanations.

@Pipe({
  name: 'i18n',
  pure: false
})