我正在开发我的项目,基本上想实现多语言 Web 应用程序。我正在使用
ngx-translate
来实现这一点。现在,我在尝试使用 ngx-cookie-consent
实现 cookie bar 时遇到了问题。
我有两种语言:en|ru
,当我单击按钮更改语言时 - 除了 cookiebar 之外,整个应用程序都会被翻译。也许您遇到过这样的问题,请给出一些提示您是如何解决的。
如有任何帮助,我们将不胜感激。
这是我如何将翻译消息加载到 cookie-consent 中的代码:
this.translateService
.get(['FOOTER.COOKIES'])
.subscribe(data => {
console.log(data)
this.ccService.getConfig().content = this.ccService.getConfig().content || {} ;
// Override default messages with the translated ones
this.ccService.getConfig().content.message = data['FOOTER.COOKIES'];
this.ccService.destroy();//remove previous cookie bar (with default messages)
this.ccService.init(this.ccService.getConfig()); // update config with translated messages
});
}
您可以在语言更改时订阅并在每次发生更改时进行配置,而不是在首次加载应用程序时仅配置一次 cookie 同意(至少您的代码中似乎是这样):
export class MyComponent implements OnInit {
ngOnInit() {
this.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
this.configureCookieConsent();
});
this.configureCookieConsent();
}
configureCookieConsent() {
this.translateService
.get(['FOOTER.COOKIES'])
.subscribe(data => {
console.log(data)
this.ccService.getConfig().content = this.ccService.getConfig().content || {} ;
// Override default messages with the translated ones
this.ccService.getConfig().content.message = data['FOOTER.COOKIES'];
this.ccService.destroy();//remove previous cookie bar (with default messages)
this.ccService.init(this.ccService.getConfig()); // update config with translated messages
});
}
}
}
我使用了一个组件作为示例,但当然它应该放在您当前配置 cookie 同意的任何位置
就我而言,我使用 angular-l10n 进行翻译,所以我在翻译时错误地填充了新的同意。问题是,在使用 ngx-cookie 同意时,每当您初始化同意时,它都会添加到屏幕上,因此您需要在初始化新同意之前销毁当前同意(确保有同意销毁,否则会抛出据我所知是错误的):
ngOnInit(): void {
this.translationOnChangeSubscription = this.translation
.onChange()
.subscribe({
next: (data) => {
this.ccService.destroy();
this.setCookieConsentBanner();
},
});
}
setCookieConsentBanner(): void {
this.ccService.init({
content: {
message: this.translation.translate('COOKIE_CONSENT_MESSAGE'),
deny: this.translation.translate('DECLINE_COOKIE'),
allow: this.translation.translate('ALLOW_COOKIE'),
learnMore: this.translation.translate('ALLOW_COOKIE'),
link: this.translation.translate('LEARN_MORE_COOKIE'),
href: 'https://your-privacy-policy-url',
},
});
}
ngOnDestroy() {
this.translationOnChangeSubscription.unsubscribe();
this.ccService.destroy();
}