【问题标题】:My variable keeps returning to default boolean value and my subscription won't proc from an observable我的变量不断返回到默认布尔值,我的订阅不会从可观察到的
【发布时间】:2021-05-12 12:51:38
【问题描述】:

我是 Angular/Node.js 的初学者,我正在做一个项目作为练习。 我在使用订阅和可观察对象时遇到了身份验证问题。

虽然我的身份验证有效,但我试图在成功的身份验证时隐藏我的登录/注册按钮,并改为显示一个注销按钮。

我使用 '*ngIf="userIsAuthenticated"' 来显示我的注销并使用 '*ngIf="!userIsAuthenticated"' 来隐藏注册/登录按钮。

在我的 authService 类文件中,我有这个:

private authStatusListener = new Subject<boolean>();

constructor(private http: HttpClient, private router: Router) {}

getAuthStatusListener() {
return this.authStatusListener.asObservable();}

login(email: string, nickname: null, password: string ) {
const authData: AuthData = {
  email: email,
  nickname: nickname,
  password: password,
};
this.http
  .post<{token: string}>(BACKEND_URL + '/login', authData)
  .subscribe((response) => {
    const token = response.token;
    this.token = token;
    this.authStatusListener.next(true);
    this.router.navigate(["/"]);
  });}

在我的组件 .ts 文件中,我有这个:

private authListenerSubs: Subscription;
userIsAuthenticated = false;

constructor(
private authService: AuthService,
public reviewService: ReviewService)

ngOnInit() {

this.authListenerSubs = this.authService
  .getAuthStatusListener()
  .subscribe((isAuthenticated) => {
    console.log('testing if this runs');
    console.log(this.userIsAuthenticated);
    this.userIsAuthenticated = isAuthenticated;
    console.log(this.userIsAuthenticated);
  });
console.log(this.userIsAuthenticated);
this.authListenerSubs = this.authService
  .getAuthStatusListener()
  .subscribe();}

我放了一堆 console.logs 来查看我的变量的行为。您也可能注意到看似无用的代码this.authListenerSubs = this.authService .getAuthStatusListener() .subscribe(); 但是如果这段代码不在该代码之下,我在订阅方法中的任何日志都不会由于某种原因而执行,我不知道为什么会这样或者这些事情是如何相关的。

主要问题是 this.userIsAuthenticated 不会被更新。 我的日志说该值应该从 false 开始,然后按应该的方式更改为 true,但是当它完成订阅时,它会立即返回 false 值,即使它不应该因为它被更改并且我无法将其改回 false。

谁能帮帮我?

【问题讨论】:

  • 我注意到 login 方法没有在任何地方调用。它与问题相关吗?

标签: angular typescript observable subscription subscribe


【解决方案1】:

Subject 不存储该值。这就是为什么每次订阅后的过程就像从头开始一样。你应该改用BehaviorSubject

你可以阅读更多关于区别here

【讨论】:

  • @perun_the_mighty 你有机会检查我的答案吗?它对你有用还是你需要一些额外的信息或解释?
  • 谢谢,这确实完美地解决了问题!非常感谢! ^_^
猜你喜欢
  • 2019-02-24
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
相关资源
最近更新 更多