angular - 如何转换 Observable到其他 Observable
问题描述
我想使用 Transloco 并从现有的 REST API 而不是 i18n 文件中收集翻译。我用休息服务调用替换了 TranslocoHttpLoader 中的行:
getTranslation(lang: string): Observable<Translation> {
// return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
return this.translationService.fetchTranslations();
}
Translation
Transloco 类型在哪里:
export declare type Translation = HashMap;
export declare type HashMap<T = any> = {
[key: string]: T;
};
翻译 REST API 正在返回:
{
"languageKeys": [
{
"key": "hello",
"value": "hello transloco"
},
...
]
}
所以
export class TranslationRest {
languageKeys: LanguageKeyRest[] = [];
}
export class LanguageKeyRest {
constructor(public key: string, public value: string) {}
}
所以我需要“转换”Observable<TranslationRest>
成Observable<Translation>
被 Transloco 消耗:
翻译服务
public fetchTranslations(): Observable<Translation> {
const response: Observable<TranslationRest> = this.httpClient.post<TranslationRest>(this.url, this.body, {'headers': this.headers});
return this.convert1(response);
}
这种最简单的(用于测试目的)convert1
方法按预期工作:
private convert1(response: Observable<TranslationRest>): Observable<Translation> {
return of({hello: 'hello transloco'})
}
html:
{{'hello' | transloco}}
在浏览器中显示:hello transloco
但是如何实现真正的转换呢?我试图按照如何在 Angular 中管道/映射 Observable 但没有运气:
private convert2(response: Observable<TranslationRest>): Observable<Translation> {
return response.pipe(
map((res: TranslationRest) => res.languageKeys.map(item =>{
item.key: item.value
}))
)
}
解决方案
你转换不正确
private convert2(response: Observable<TranslationRest>): Observable<Translation> {
return response.pipe(
map((res: TranslationRest) => res.languageKeys.reduce((obj, item) => ({
...obj,
[item.key]: item.value,
}), {}))
)
}
推荐阅读
- python - 绘制水平线(matplotlib)
- c# - 使用 transform.position 时的 2D 碰撞检测。如何启用?
- typescript - 如何使用括号表示法检查打字稿中的无效性
- c# - fopen_s 仅在通过 c# windows 窗体启动 c++ exe 时失败
- c - 链表递归函数中的 malloc 和 free
- java - 如何在用 Java 编写的多模块播放项目中运行单元测试
- java - Monitoring replicas with Spring Boot Admin on Kubernetes
- java - 高性能的java中的Json转换
- c++ - 读取访问冲突当前为 0xCDCDCDCD,链接列表窗口
- python - 异常处理不适用于开放 python