我有一个解析消息密钥的管道,并根据区域设置返回消息。
但我想要有角度等待,直到我的服务将完成它加载消息,并且只有在继续呈现主页面之后。我的本地化管道使用的地方。 如何让它发挥作用?
服务:
@Injectable()
export class I18nService implements OnInit {
private cachedMessages: {string: string};
activeLocale:I18Enum = null;
constructor(private http: Http) {
this.reloadLocale(I18Enum.ru);
}
ngOnInit(): void {
this.reloadLocale(I18Enum.ru);
}
getMessage(key: string) {
if (this.cachedMessages) {
return this.cachedMessages[key];
}
}
reloadLocale(locale: I18Enum) {
this.activeLocale = locale;
this.http.get(basePath + i18nPath + I18Enum[locale]).subscribe(
res => {
this.cachedMessages = res.json();
}
);
}
}
和管道:
@Pipe({name: 'i18nPipe'})
export class I18nPipe implements PipeTransform {
constructor(private i18Service: I18nService) {
}
transform(value: any, args: any): any {
return this.i18Service.getMessage(value);
}
}
答案 0 :(得分:3)
确定。最后我做到了。我找到了这个答案,它帮助了我。 https://stackoverflow.com/a/40379803/5203127
所以我的代码现在如下所示:
服务:(添加了initMessages方法)
evaluate_generator
我的引导程序:(已添加APP_INITIALIZER提供程序)
@Injectable()
export class I18nService {
private cachedMessages: {string: string} = null;
activeLocale: I18Enum = null;
constructor(private http: Http) {
}
getMessage(key: string) {
if (this.cachedMessages) {
return this.cachedMessages[key];
}
}
reloadLocale(locale: I18Enum) {
this.activeLocale = locale;
this.http.get(basePath + i18nPath + I18Enum[locale]).subscribe(
res => {
this.cachedMessages = res.json();
}
);
}
initMessages(locale: I18Enum) {
this.activeLocale = locale;
return new Promise((resolve, reject) => {
this.http.get(basePath + i18nPath + I18Enum[locale]).map(res => res.json()).catch((error: any): any => {
reject(false);
return Observable.throw(error.json().error || 'Server error');
}).subscribe((callResult: {string: string}) => {
this.cachedMessages = callResult;
resolve(true);
});
});
}
}