0

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.

  • Does this answer your question? [Angular/RxJS When should I unsubscribe from \`Subscription\`](https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription) – MoxxiManagarm Jul 05 '22 at 07:17
  • where's the memory leak exactly? – akotech Jul 05 '22 at 07:39
  • I think that I was in mistake, because when I wrote the setInterval function in the subscription, I actually didn't clear the id of this interval when the subscription complete. It's working as expected. Thank you. – Dimitar Dimitrov Jul 05 '22 at 08:53

1 Answers1

0

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;
    }
  },
});
MikkelDalby
  • 142
  • 2
  • 11
  • 1
    Good idea, but even that is not needed. The source observable will complete after the first emission, because he returns `this.http.post ...`. He does not return the subject. Your suggestion works fine for places where he subscribes to the `user` subject, but if we think about it, it's not very practical because it's only a plain subject. In order to use it, he should subscribe to it before calling `login`, which is a bit too much to remember. The whole solution could probably be simpler. – Octavian Mărculescu Jul 05 '22 at 07:44