gpt4 book ai didi

javascript - Angular2 等待 JSON 文件加载

转载 作者:太空狗 更新时间:2023-10-29 17:57:57 25 4
gpt4 key购买 nike

目前我正在加载一个 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 被注入(inject)到我的 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 文件加载所有值吗?

最佳答案

我认为您可以稍微调整一下您的服务和管道,以便在后台准备好/加载数据时进行处理。

首先添加一个 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 .

关于javascript - Angular2 等待 JSON 文件加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35982001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com