Angular2 dynamic pipe

风流意气都作罢 提交于 2020-01-05 05:06:11

问题


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


来源:https://stackoverflow.com/questions/40565167/angular2-dynamic-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!