目前我正在加载一个 JSON 文件,如下所示:
翻译服务.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];
}
}
Run Code Online (Sandbox Code Playgroud)
localizable.it.strings
{
"home.nav.calendar": "Calendar",
...
}
Run Code Online (Sandbox Code Playgroud)
我TranslationService
被注入我的HomeComponent
但问题是当我尝试通过管道读取这些值时,它们仍然需要在页面呈现时加载。
翻译.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);
}
}
Run Code Online (Sandbox Code Playgroud)
知道如何在加载任何页面之前从 JSON 文件加载所有值吗?