Search code examples
angularrxjsobservablesubscriptionbehaviorsubject

Angular 2 & RxJS: Subject.next not working in some cases


I have this service (authApiService.login() works just fine, gets expected data):

@Injectable({ providedIn: 'root' })
export class AuthService {
  private loggedIn: Subject<boolean> = new BehaviorSubject<boolean>(
    !this.isTokenExpired()
  );

  get isLoggedIn(): Observable<boolean> {
    return this.loggedIn.asObservable();
  }

  logout(): void {
    /* ... */
    this.loggedIn.next(false);
  }

  login(login: string, password: string): Observable<LoginResult> {
    return this.authApiService.login(login, password).pipe(
      map((result) => {
        if (result) {
          /* ... */
          this.loggedIn.next(true);
        }
        return result;
      })
    );
  }

}

And following component functions (processLogin() works just fine, tested without subscriptions):

 ngOnInit(): void {
    this.loggedInSub = this.authService.isLoggedIn.subscribe(
      (loggedIn: boolean) => this.processLogin(loggedIn)
    );
  }

After I log out from my application (calling logout() from service), this .next() actually emits false value and subscription inside component (declared in ngOnInit()) works. But when I call service's login() method, debugger shows that this.loggedIn.next(true); is executed, but subscription inside component does not execute provided code. I have no idea why logout() => next(false) works, and login() => next(true) doesn't. All mentioned methods without implementation are tested and work just fine. Please help!

EDIT:

Just noticed - login() => next(true) does not work, but page refreshing work (page behaves like "true" in subscription)


Solution

  • After 2 months (and 6 at all) I fixed it. It was only about removing AuthService from module providers. It seems like different instances were created in different modules. But I'm not an Angular expert, if anyone know how to explain it, then please try.