Search code examples
angulartypescriptobservablesubscriptionsubscribe

My variable keeps returning to default boolean value and my subscription won't proc from an observable


I am a beginner in Angular/Node.js and I am doing a project as a practice. I got stuck in an authentication problem using subscriptions and observables.

While my authentication works, I am trying to visually hide my login/signup buttons on successful authentication, and show a logout button instead.

I am using the '*ngIf="userIsAuthenticated"' to show my logout and '*ngIf="!userIsAuthenticated"' to hide signup/login buttons.

In my authService class file I have this:

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(["/"]);
  });}

In my component .ts file i have this:

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();}

I put a bunch of console.logs to see how my variable behaves. Also you probably notice the seemingly useless code this.authListenerSubs = this.authService .getAuthStatusListener() .subscribe(); but none of my logs inside the subscribe method won't execute for some reason if this piece of code isn't below that code, and I have no idea why that is the case or how these things are related.

The main problem is that this.userIsAuthenticated won't be updated. My logs say that the value starts at false as it should be, then gets changed to true as it should be, but when it finishes the subscribe, it then immediately returns to false value, even though it shouldn't as it was changed and nowhere do I change it back to false.

Can anyone please help me?


Solution

  • Subject does not store the value. That’s why after each subscription the process is like starting from the beginning. You should use BehaviorSubject instead

    You can read more about the difference here