2016-11-12 103 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項目建議使用它的指令而不是它的管道。也就是說,如果您的實現看起來像是在您的問題中,並且不需要內插或任何其他內容,那麼獲得翻譯將會非常快速,並且可能足夠快。 –