我目前正在开发应用程序,我们需要使用不同的品牌和翻译。为此,我需要从查询参数中获取一些信息,这对于获取在 ngOnInit() 期间完成的所有资产(图像/图标/徽标)效果很好,但我在翻译方面遇到问题。我创建了自定义翻译加载器,如下所示:
export class TranslationFileLoader implements TranslateLoader {
private tenant: string | null = "";
private sp: string | null = "";
constructor(private http: HttpClient, private actRoute: ActivatedRoute) {
this.actRoute.queryParams.subscribe(params => {
if (params !== null) {
this.tenant = params["tenant"];
this.sp = params["sp"];
}
});
}
getTranslation(lang: string): Observable<any> {
return this.http.get(environment.blobUrl + "/" + this.tenant.replace(/[.]/g,'')+"/i18n/" + this.sp?.toLowerCase() + "/" + `${lang}` + ".json");
}
}
但是当加载器初始化时,查询参数为空,然后翻译链接包含未定义。有没有办法以某种方式获取这些参数或者以不同的方式做?我考虑过在 localStorage 中设置这两个变量。
尝试修改代码,以便首先访问路由快照(无需订阅!)并获取数据,然后返回 API 调用!
因为这是一个时序问题,订阅是在调用 getTranslation 方法之后执行的,因此你可能会遇到这个问题!
export class TranslationFileLoader implements TranslateLoader {
private tenant: string | null = "";
private sp: string | null = "";
constructor(private http: HttpClient, private actRoute: ActivatedRoute) {
}
getTranslation(lang: string): Observable<any> {
const params = this.actRoute?.snapshot?.params;
// if no data then it will fallback to the default values you set using `||` condition in javascript since lhs is false!
this.tenant = params?.["tenant"]; // you can also give fallback data by giving: params?.["tenant"] || 'asdf';
this.sp = params?.["sp"]; // you can also give fallback data by giving: params?.["tenant"] || 'en';
return this.http.get(environment.blobUrl + "/" + this.tenant.replace(/[.]/g,'')+"/i18n/" + this.sp?.toLowerCase() + "/" + `${lang}` + ".json");
}
}
...