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 (将#修改为@)