Angular2动态管道 [英] Angular2 dynamic pipe

查看:218
本文介绍了Angular2动态管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用管道国际化我的应用程序:

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

}

此管道调用服务:

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

}

在组件中,我像

<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.

我尝试了ApplicationRef.tick()和NgZone.run(callback),但没有进行任何操作运气。

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 ?

谢谢

推荐答案

您的管道应标记为不纯,因为给定输入的转换结果可以即使输入没有更改也可以更改。

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.

请参见文档以获取解释。

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

这篇关于Angular2动态管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆