Search code examples
angularangular-routerangular-guards

Angular BehaviourSubject Subscribe not updated when called from component and guard


I'm sorry if my question looks silly.

I try to implement behaviorsubject in my service and then call it from my login component.

This is my service

private currentTokenSubject: BehaviorSubject<AuthResponse>;
  public currentToken: Observable<AuthResponse>;

constructor(private httpClient: HttpClient) {
    this.currentTokenSubject = new BehaviorSubject<any>(localStorage.getItem(TOKEN_NAME));
    this.currentToken = this.currentTokenSubject.asObservable();
  }

public get currentTokenValue(): AuthResponse {
    // console.log('auth service: ' + this.currentTokenSubject.value)
    return this.currentTokenSubject.value;
  }

  login(usernameOrEmail:string, password: string){
    return this.httpClient.post<any>(this._loginUrl,{usernameOrEmail, password})
      .pipe(map(res => {
        //login sucess if there's jwt token in the response
        if(res && res.accessToken){
          //store user details and jwt token in local storage to keep user logged in between page refresh
          localStorage.setItem(TOKEN_NAME, res.accessToken);
          this.currentTokenSubject.next(res.accessToken);
          console.log(this.currentTokenValue); // It's changed
        }
        return res;
      }));
  }

here the code in my component

constructor(
    private formBuilder: FormBuilder, 
    private authService: AuthService, 
    private router: Router,
    private route: ActivatedRoute,
    private alertService: AlertService
    ) {
      this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '';

      if(this.authService.currentTokenValue){
        this.router.navigate([this.returnUrl]);
      }
  }

onSubmit(): void{
    for (const i in this.loginForm.controls) {
      this.loginForm.controls[i].markAsDirty();
      this.loginForm.controls[i].updateValueAndValidity();
    }

    // stop here if form is invalid
    if (this.loginForm.invalid) {
      return;
    }

    const val = this.loginForm.value;
    this.isLoading = true;

    this.authService.login(val.username, val.password) // calls the service
      .pipe(first())
      .subscribe( 
        data => {
          setTimeout(() => {this.router.navigate([this.returnUrl])},500);
        },
        error => {
          this.alertService.error(error);
          this.isLoading = false;
        }
    );
  }

And this is the guard

constructor(
    private router: Router,
    private authService: AuthService
  ){}

  canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot
  ) {
    const currentToken = this.authService.currentTokenValue;
    console.log(currentToken); // return null
    if(currentToken){
      //authorized
      return true;
    }


    // not logged in : redirect to login page with return url
    //console.log(state.url)
    this.router.navigate(['login'], { queryParams : { returnUrl: state.url }});
    return false;
  }

when I tried to login console.log in the guard returns null.

Anyone can explain to me, why is it like that?

UPDATE

Nothing wrong with the application, what you must do is:

ONLY USE PROVIDERS ONCE

Import the service to @ngmodule in app.module.ts, otherwise you will create instance each component / module.


Solution

  • UPDATE

    Nothing wrong with the application, what you must do is:

    ONLY USE PROVIDERS ONCE

    Import the service to @ngmodule in app.module.ts, otherwise you will create instance each component / module.