目前我正在加载JSON文件,如下所示:
translation.service.ts
@Injectable()
export class TranslationService {
private _messages = [];
constructor(private _http: Http) {
var observable = this._http.get("/app/i18n/localizable.it.strings").map((res: Response) => res.json());
observable.subscribe(res => {
this._messages = res;
});
}
getTranslationByKey(key: string, args?: any[]) {
return this._messages[key];
}
}
localizable.it.strings
{
"home.nav.calendar": "Calendar",
...
}
我的TranslationService
被注入我的HomeComponent
,但问题是当我尝试通过管道读取这些值时,仍然需要在呈现页面时加载它们。
translate.pipe.ts
@Pipe({name: 'translate'})
export class TranslatePipe implements PipeTransform {
constructor(private _translation: TranslationService) {}
transform(value: string, args: string[]) : any {
return this._translation.getTranslationByKey(value);
}
}
知道如何在加载任何页面之前从JSON文件加载所有值吗?
答案 0 :(得分:1)
我认为您不应该尝试让代码同步。相反,让TranslationService
告诉你什么时候准备就绪:
export class TranslationService {
// ...
get isReady() {
return !!this._messages;
}
}
然后,只有当_messages
不为空时,管道才能返回翻译。
export class TranslatePipe implements PipeTransform {
// ...
transform(value: string, args: string[]) : any {
return this._translation.isReady
? this._translation.getTranslationByKey(value) : null;
}
}
答案 1 :(得分:1)
我认为您可以调整一下您的服务和管道,以便在数据准备/加载时进行处理。
首先添加一个observable以在服务中加载数据时通知:
@Injectable()
export class TranslationService {
private _messages = {};
private translationLoaded : Observable<boolean>;
private translationLoadedObserver : Observer<boolean>;
constructor(private _http: Http) {
this.translationLoaded = Observable.create((observer) => {
this.translationLoadedObserver = observer;
});
var observable = this._http.get("app/i18n/localizable.it.strings").map((res: Response) => res.json());
observable.subscribe(res => {
this._messages = res;
this.translationLoadedObserver.next(true);
});
}
getTranslationByKey(key: string, args?: any[]) {
return this._messages[key];
}
}
管道可以订阅此observable,以async
的方式透明地更新消息的值:
@Pipe({
name: 'translate',
pure: false // required to update the value when data are loaded
})
export class TranslatePipe implements PipeTransform {
constructor(private _ref :ChangeDetectorRef, private _translation: TranslationService) {
this.loaded = false;
}
transform(value: string, args: string[]) : any {
this.translationLoadedSub = this._translation.translationLoaded.subscribe((data) => {
this.value = this._translation.getTranslationByKey(value);
this._ref.markForCheck();
this.loaded = true;
});
if (this.value == null && this.loaded) {
this.value = this._translation.getTranslationByKey(value);
}
return this.value;
}
_dispose(): void {
if(isPresent(this.translationLoadedSub)) {
this.translationLoadedSub.unsubscribe();
this.translationLoadedSub = undefined;
}
}
ngOnDestroy(): void {
this._dispose();
}
}
这是相应的plunkr:https://plnkr.co/edit/VMqCvX?p=preview。