我正在构建一个应用程序,您可以随时在两种语言之间进行切换。我有一个模拟服务,它提供了我使用的短语。当用户点击语言链接时,模拟服务中的语言会发生变化,但是当我收到短语时,我需要以某种方式听取更改,因此服务正在返回我想要的语言中更新的短语。
LangService.ts:
activeLang :string = 'EN';
getPhrase(phrase :string) :string{
if(this.activeLang == 'EN'){
return this.EN[phrase];
} else {
return this.CZ[phrase];
}
}
changeLanguage(lang :string) :void{
if(lang == 'EN' || lang == 'CZ'){
this.activeLang = lang;
}
}
然后是一些OtherComponent.ts:
setPhrase(phrase :string){
this._langService.getPhrase(phrase);
// Here I need to subscribe to getPhrase to get the latest updates
// If I'm right and if it's possible
}
更新
我做了一些更正。 LangService现在具有我们可以监听的Observable,但是监听器仅适用于触发方法changeLanguage()的组件。我希望能够从我的NavigationComponent更改语言并捕获一些OtherComponent中的更改。
LangService.ts:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class LangService {
private activeLang = 'EN';
private activeLangSubject = new Subject<string>();
activeLang$ = this.activeLangSubject.asObservable();
// Objects EN and CZ with properties, etc.
getPhrases(phrases :Array<string>){
if(this.activeLang == 'EN'){
let response = <any>{};
for(let i = 0; i < phrases.length; i++){
response[phrases[i]] = this.EN[phrases[i]];
}
console.log('refresh');
return JSON.stringify(response);
} else {
let response = <any>{};
for(let i = 0; i < phrases.length; i++){
response[phrases[i]] = this.CZ[phrases[i]];
}
return JSON.stringify(response);
}
}
changeLanguage(lang :string){
if(lang == 'EN' || lang == 'CZ'){
this.activeLang = lang;
this.activeLangSubject.next(lang);
}
}
NavComponent.ts:
import { Component, OnInit } from '@angular/core';
import { LangService } from '../lang.service';
@Component({
moduleId: module.id,
selector: 'app-nav',
templateUrl: 'nav.component.html',
styleUrls: ['nav.component.css'],
providers: [LangService]
})
export class NavComponent implements OnInit {
langs :Array<string> = ['EN', 'CZ'];
constructor(
private _langService :LangService) {
}
changeLanguage(lang :string) :void{
this._langService.changeLanguage(lang);
}
}
使用NavComponent.html:
<li *ngFor="let lang of langs">
<a (click)="changeLanguage(lang)">{{ lang }}</a>
</li>
OtherComponent.ts:
import { Component, OnInit } from '@angular/core';
import { LangService } from '../lang.service';
import { NavComponent } from '../nav/nav.component';
@Component({
moduleId: module.id,
selector: 'all-notes',
templateUrl: 'notes.component.html',
providers: [NoteService, LangService],
directives: [NavComponent]
})
export class NotesComponent implements OnInit {
mode = 'Observable';
postPhrases :Array<string> = [
"alertTitle", "alertText", "options", "detailsBtn","editBtn","deleteBtn",
"addBtn", "serverResp", "actionMessage", "responseMessage", "note"
];
getPhrases :Object;
constructor(
private _langService :LangService) {
}
ngOnInit() {
this.updatePhrases(this.postPhrases);
// This one doesn't work
this._langService.activeLang$.subscribe(
success => this.updatePhrases(this.postPhrases),
error => console.log(error),
() => console.log('complete')
);
}
updatePhrases(phrases :Array<string>) :void {
this.getPhrases = JSON.parse(this._langService.getPhrases(phrases));
}
}
我现在的问题是如何在OtherComponent上监听更改,因此我可以使用方法updatePhrases()来更新短语。
答案 0 :(得分:1)
这听起来像是你会用管道来的东西:
import { Pipe, PipeTransform, Injectable } from '@angular/core'
@Injectable()
@Pipe({ name: 'myTranslatePipe' })
export class IndicatorHeadersPipe implements PipeTransform {
public transform(
phrase: string,
activeLang: string
) {
if(activeLang == 'EN'){
return this.EN[phrase];
} else {
return this.CZ[phrase];
}
}
}
不要忘记将管道添加到NgModule
声明
然后,在您的组件中
@Component({
selector: 'my-selector',
template: `
<div>{{ 'My text' | myTranslatePipe : activeLang }}</div>
`,
})
export class PageIndicatorComponent {
private activeLang: string
changeLanguage(lang :string) :void{
if(lang == 'EN' || lang == 'CZ'){
this.activeLang = lang;
}
}
}
但是,我建议您只使用翻译模块,例如ng2-translate
答案 1 :(得分:0)
所以基本上我需要的是用3个变量创建一个服务LangService。
activeLang: string 'EN';
activeLangSubject: Subject<string> = new Subject<string>();
activeLangObservable: Observable<string> = this.activeLangSubject.asObservable();
之后,我需要将LangService添加到正确的范围。我希望它是全局的,所以我把它作为main.ts
文件中的bootstrap方法的提供者。
bootstrap(AppComponent, [LangService]);
当然我需要在将它提供给bootstrap之前导入它。
在引导程序中提供后,我需要做的就是:
constructor(private _langService: LangService) {}
中注入它,订阅
ngOnInit() {
this._langService.langServiceObservable.subscribe(
response => console.log('Changed! Active Language: ' + response),
error => console.log('Error! Description: ' + error)
);
}
如果您不使用ngOnInit(),您还可以订阅构造函数内的更改()