ngx-translate 带角材料 2 MdSnackBar [英] 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()
方法从 observable 中返回正确的字符串值.
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 });
});
}
这篇关于ngx-translate 带角材料 2 MdSnackBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!