How must I unsubscribe from a subscription of subject after logout? My user is actually my subject

523 Views Asked by At

I have an authService and in there I have a login method that looks like that:

user = new Subject<User>();

login(username: string, password: string): Observable<User> {
return this.http
  .post<User>('http://localhost:4000/users/authenticate', {
    username: username,
    password: password,
  })
  .pipe(
    tap((resData) => {
      const user = new User(
        resData.firstName,
        resData.lastName,
        resData.username,
        resData.id,
        resData.token
      );
      localStorage.setItem('user', JSON.stringify(user));
      this.user.next(user);
    })
  );

}

I use this function in my AuthComponent when I pass my username and password:

 onSubmit() {
const loginForm = this.loginForm;
if (!loginForm) {
  return;
}
const username = this.loginForm.value.username;
const password = this.loginForm.value.password;

this.authService.login(username, password).subscribe({
  next: () => this.router.navigate(['/monthly-deposits']),
  error: (error) => {
    if (!!error.error.message) {
      this.error = error.error.message;
    }
  },
});
this.loginForm.reset();

}

I use a button in my header to logout and I call a function from my authService:

 logout() {
this.user.next(null);
this.router.navigate(['/login']);
localStorage.removeItem('user');

}

How can I remove the subscription, because it means memory leak. Thanks for your attention. I’m looking forward to your reply.

1

There are 1 best solutions below

1
MikkelDalby On

How about making the login subscription like this, with pipe(take(1)). Then the subscription should only run once at be closed after that.

this.authService.login(username, password).pipe(take(1)).subscribe({
  next: () => this.router.navigate(['/monthly-deposits']),
  error: (error) => {
    if (!!error.error.message) {
      this.error = error.error.message;
    }
  },
});