【问题标题】:Auth guard is not waiting for local storage身份验证守卫不等待本地存储
【发布时间】:2018-06-16 18:49:28
【问题描述】:

我有基于本地存储值(如果存在或不存在)的身份验证保护。但是在从本地存储中获取值之前,canActivate() 函数会返回空值。我能做些什么来实现这个机制?

我的代码

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    this.check = this.usr.getUserLoggedIn().subscribe((data) => {
      // this.check = data;
      console.log(data);
    });
    // console.log('check', this.check);
    if (this.check === true) {
      return true;
    } else {
      // alert('else');
      this.router.navigate(['/authentication/login']);
      return false;
    }
}

服务功能代码:

getUserLoggedIn() {
    return this.localStorage.getItem('isUserLoggedIn');
    // return this.isUserLoggedIn;
  }

【问题讨论】:

  • 在 setTimeout 方法中添加您的逻辑,以便有时间获取本地存储值。延迟值不需要设置,也可以为0。
  • 因为你的 canActivate 方法实际上并没有返回一个可观察的布尔值
  • @jonrsharpe 我如何将这个设置为 true 的本地存储值传递给 canActivate 函数,因为我必须将此值传递给 canActivate 以进一步路由是否有任何方法可以实现这种机制?
  • 你不在方法中订阅,你返回一个 observable 并让框架订阅。将签名更改为仅包含 Observable&lt;boolean&gt; 作为有效返回,然后查看您收到的警告。

标签: angular angular6


【解决方案1】:

你可以试试这个解决方案

服务功能代码:

getUserLoggedIn() {
    return localStorage.getItem('isUserLoggedIn');
    // return this.isUserLoggedIn;
}

setUserLoggedIn(data) {
    localStorage.setItem('isUserLoggedIn',data);
}

ts 文件代码:

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    this.check = this.usr.getUserLoggedIn();
    // console.log('check', this.check);
    if (this.check) {
      return true;
    } else {
      // alert('else');
      this.router.navigate(['/authentication/login']);
      return false;
    }
}

【讨论】:

  • 我认为在 Angular 6 中,我们无法为存储设置值,因为您在这里提到它就像 this.localStorage.setItem('isUserLoggedIn', isUserLoggedIn).subscribe(() =&gt; { });
  • 它与 Angular 6 一起使用,因为 localStorage 是浏览器属性。 setUserLoggedIn(data) { localStorage.setItem('isUserLoggedIn',data); }
  • 谢谢兄弟的建议,我使用 ngx-webstorage 而不是使用 localstorage,它解决了我的问题,它返回简单的值而不是 observable。 :)
  • 是的,答案非常好,非常感谢。快乐编码:)
猜你喜欢
  • 2019-11-30
  • 1970-01-01
  • 2021-05-01
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 2018-11-21
相关资源
最近更新 更多