首页 > 解决方案 > 从组件和保护调用时,Angular BehaviourSubject 订阅未更新

问题描述

如果我的问题看起来很愚蠢,我很抱歉。

我尝试在我的服务中实现 behaviorsubject,然后从我的登录组件中调用它。

这是我的服务

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

这是我组件中的代码

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

当我尝试登录 console.log 时,守卫返回 null。

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

更新

应用程序没有问题,您必须做的是:

仅使用一次提供商

将服务导入 app.module.ts 中的 @ngmodule,否则您将为每个组件/模块创建实例。

标签: angularangular-routerangular-guards

解决方案


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

public get currentTokenValue(): AuthResponse {
    return this.currentTokenSubject.getValue();
}

推荐阅读