繁体   English   中英

Angular 8:无法从服务中正确获取价值

[英]Angular 8: Can't correctly get value from service

我有一个简单的身份验证服务,仅用于测试,因为我正在学习设置 localStorage 值的 Angular

一般服务:

isAuthenticated = new Subject();
autoLogin = new Subject();

认证服务:

if (response.message === 'Logged in') {
    localStorage.setItem('isLoggedIn', '1');
    this.generalS.isAuthenticated.next(true);
  } else {
    this.generalS.isAuthenticated.next(false);
  }

授权组件

isAuthSub: Subscription;
// in the submit function ...
this.authS.login(userData);
this.isAuthSub = this.generalS.isAuthenticated.subscribe( (data) => {
  if (data) {
    console.log('Yes');
    this.route.navigate(['recipes']);
  } else {
    console.log('No');
  }
});

在控制台中我得到Yes

在应用组件中

const isLoggedIn = localStorage.getItem('isLoggedIn');
if (!isLoggedIn || isLoggedIn !== '1') {
  this.generalS.autoLogin.next(false);
  this.generalS.isAuthenticated.next(false);
} else {
  console.log('loggenInValue: ' + isLoggedIn);
  this.generalS.autoLogin.next(true);
  this.generalS.isAuthenticated.next(true);
}

我在控制台中得到了这个

loggenInValue: 1

所以 autoLogin 和 isAuthenticated 主题应该保持true作为一个值

我在标头组件中收听此值以显示或隐藏login链接,但它不记录任何内容

在标头组件中

authSub: Subscription;
isAuthenticated: boolean;
ngOnInit() {
  this.authSub = this.generalS.isAuthenticated.subscribe( (data: boolean) => {
    this.isAuthenticated = data;
    console.log('authenticated: ' + data);
  });
}

我没有从这个部分得到任何日志。 关于解决这个问题的任何想法? [我知道我不应该像这样检查自动登录功能,而只是为了测试以检查 localStorage 值并根据它更改其他值]

因为我不知道代码在你的 authService 中的确切位置。 我假设您在订阅之前调用 next(),这意味着还没有任何订阅者。 主题只向现有的订阅者发出事件,而不是未来的订阅者。

如果您只想获取订阅的最新值,您可以轻松切换到 ReplaySubject:

isAuthenticated = new ReplaySubject(1);
autoLogin = new ReplaySubject(1);

https://rxjs-dev.firebaseapp.com/api/index/class/ReplaySubject

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM