2016-11-12 67 views
1

我使用的是管道走向国际化我的应用程序:Angular2动态管

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

但是,即使服务语言值已更改,管道结果也不会重新评估。我需要导航到任何其他路线,然后回过头来查看此更改。

我尝试了ApplicationRef.tick()和NgZone.run(回调),没有任何运气。

有关如何重新评估应用程序的每个管道而不导航到其他路线或重新加载页面的任何想法?

感谢

+0

可以使用伪造的参数手动https://plnkr.co/edit/GsSJCRge8ulBzaRFokzj?p=preview触发管或者你必须改变你的输入字符串https://plnkr.co/edit/v6bfN8ri8lYuAhWrb3TZ? p =预览 – yurzui

+0

权,但会意味着无处不在加入这个假PARAM我国际化的东西 – Max

回答

2

你管应标记为不纯正,因为虽然输入并没有改变其对于给定的输入转换的结果甚至可以改变。

查看the documentation的解释。

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

这正是我需要的东西,非常感谢! (请注意,下次阅读FULL文档...) – Max

+0

但是,看起来性能明智,这不是一个好的选择,特别是对于一个国际化的i18n管道而言。任何机会我都可以手动触发对“纯”管道的重新评估? – Max

+0

我不这么认为。一条指令可能比这条管道更好。 AngularJS 1.x过滤器具有相同的性能问题,并且$ translate项目建议使用它的指令而不是它的管道。也就是说,如果您的实现看起来像是在您的问题中,并且不需要内插或任何其他内容,那么获得翻译将会非常快速,并且可能足够快。 –