用角材料2 MdSnackBar进行ngx-translate [英] ngx-translate with angular material 2 MdSnackBar
问题描述
我是TS和Angular 4的新手.我需要向用户展示在角材料2 MdSnackBar
中的翻译后的 CLOSE
单词.我了解您可以从如下代码中调用ngx-translate翻译服务:
I'm new to TS and Angular 4. I need to be able to show a user a translated CLOSE
word inside the angular material 2 MdSnackBar
. I've understood that you can call the ngx-translate translation service from within the code like this:
this.translate.get('ERROR.CLOSE').subscribe((res: string) => {
console.log(res);
});
问题是我需要能够在名为 MdSnackBar
的有角材质2元素中显示此内容.
The thing is that I need to be able to show this inside an angular material 2 element called MdSnackBar
.
我想这样执行它:
this.snackBar.open(error, this.getCloseWord(), {
duration: 10000,
})
private getCloseWord() {
this.translate.get('ERROR.CLOSE').subscribe((res: string) => {
console.log(res);
});
}
但是我不知道如何使 getCloseWord()
方法从可观察对象中返回正确的字符串值.
But I don't know how to make the getCloseWord()
method to return a correct string value out of an observable.
推荐答案
请尝试以下操作:
public someMethod() {
const error = ...some error...;
...
this.translate.get('ERROR.CLOSE').subscribe(( res: string ) => {
this.snackBar.open(error, res, { duration: 10000 });
});
...
}
.get()"函数返回一个Observable,因此在订阅"get"时只需打开小吃栏即可.然后,您知道您的翻译可用了.
The ".get()" function returns an Observable so just open your snackbar when "get" is subscribed. Then you know that your translation is available.
具有多个观察者的解决方案如下:
A solution with more than one observer could be as follows:
public someMethod() {
const newObserver = new ReplaySubject();
let error = null;
let close = null;
this.translate.get('ERROR.MESSAGE').subscribe( (translation: string) => {
error = translation;
newObserver.next();
});
this.translate.get('ERROR.CLOSE').subscribe( (translation: string) => {
close = translation;
newObserver.next();
});
newObserver.subscribe( () => {
if(error && close) {
this.snackBar.open(error, close, { duration: 10000 });
}
});
}
或者最好的解决方案是将它们合并:
Or the best solution is to merge them:
import "rxjs/add/observable/forkJoin";
...
public someMethod(){
const firstTranslationObs = this.translate.get('ERROR.MESSAGE');
const secondTranslationObs = this.translate.get('ERROR.CLOSE');
Observable.forkJoin([firstTranslationObs, secondTranslationObs])
.subscribe(results => {
let error= results[0];
let close = results[1];
this.snackBar.open(error, close, { duration: 10000 });
});
}
这篇关于用角材料2 MdSnackBar进行ngx-translate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!