如何解决Angular:如果localStorage中存在变量,如何重定向到给定的url?
当我加载应用程序时,默认的网站语言是英语。但是,当我将语言更改为法语时,我正在将一个包含该特定站点语言环境路径的变量存储在本地存储器中。我下次需要加载应用程序时,它应该检查我在本地存储中存储的变量是否具有值,然后将我重定向到我之前选择的特定站点语言环境。当前,我的实现给了我一个无限循环,这样当我加载应用程序时,它会不断重新加载而不会停止。 我该怎么办? 这是我所做的:
// header component
export class HeaderComponent implements OnInit {
languages = [{
code: 'en-US',label: 'English'
},{
code: 'am',label: 'Amharic'
},];
constructor(
@Inject(LOCALE_ID) public localeId: string,@Inject(APP_BASE_HREF) public baseHref: string,public location: Location
) {}
cacheLocalePreference() {
if (this.localeId === 'en-US') {
localStorage.setItem('localePath',location.href);
} else if (this.localeId === 'am') {
localStorage.setItem('localePath',location.href);
}
}
}
// index component
export class IndexComponent implements OnInit {
localePath: any;
defaultPathDev: string;
defaultPathLive: string;
constructor(
public route: Router,public location: Location,@Inject(LOCALE_ID) public localeId: string,@Inject(APP_BASE_HREF) public baseHref: string
) {
this.defaultPathDev = 'http://localhost:4200';
this.defaultPathLive = 'http://localhost/inibla';
this.localePath = localStorage.getItem('localePath');
console.log('baseHref',baseHref);
console.log('localeID',localeId);
console.log('localePath',this.localePath);
}
ngOnInit() {
if (this.localePath !== null) {
if (location.href === this.localePath) {
return;
} else {
window.location.href = this.localePath;
}
} else {
window.location.href = this.defaultPathDev;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。