Angular BehaviourSubject从组件调用时未更新订阅

问题描述 投票:0回答:1

很抱歉,我的问题看起来很傻。

我尝试在服务中实现行为主体,然后从登录组件中调用它。

这是我的服务

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

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

这里是我组件中的代码

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

这是守卫

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

当我尝试登录Guard中的console.log时返回null。

任何人都可以向我解释,为什么会这样?

angular angular-router angular-guards
1个回答
0
投票

如果要读取当前值而不是。.getValue(),则需要在BehaviourSubject上使用value。>

public get currentTokenValue(): AuthResponse {
    return this.currentTokenSubject.getValue();
}
© www.soinside.com 2019 - 2024. All rights reserved.