首页 > 解决方案 > Component variable inside subscribe function of a behavioural subject

问题描述

I have a login service component which has a behavioral subject _loginEmailId" and the method updateLoginEmailId(email:string)` to update its value as following.

private _loginEmailId = new BehaviorSubject<string>("")
currentLoginEmailId = this._loginEmailId.asObservable()

private _isLoggedIn = new BehaviorSubject<boolean>(false);
isLoggedIn$ = this._isLoggedIn.asObservable();

changeLoggedInStatus(state:boolean){
        this._isLoggedIn.next(state);
}

updateLoginEmailId(email:string){
        this._loginEmailId.next(email);
}

login(email:string, password:string){
        //returns observable
}

In Login Component I am subscribing to a login method from Login service component by passing a email ID and password captured from a reactive form. Inside this subscribe function, after receiving the response I am trying to update the _loginEmailId in the login service, by calling updateLoginEmailId(email:string) so that I can use it in another component. But I am not able to pass this.loginEmail to the updateLoginEmailId(email:string). When I log this.loginEmail inside subscribe it logs null, outside subscribe it logs the correct value. I know, this is bacause of this not referring to the component.

I have seen that=this hack, that did not work either.

How can I solve this.

My Login Component looks like this

export class LoginComponent{

  loginEmail:string;
  loginPassword:string;
 
}

login(form: NgForm){
    this.loginService.login(this.loginEmail, this.loginPassword).subscribe(
      (response) => {
        this.loginService.changeLoggedInStatus(true); //This works
        this.loginService.updateLoginEmailId(this.loginEmail); // The function is getting invoked 
            but the value for this.loginEmail is null.
        this.router.navigate(['/home']); //This works 
      },
      error => {
        console.log(error);
      }
    );
    form.resetForm();

  }

标签: javascriptangulartypescriptfrontend

解决方案


订阅是异步的,这意味着它发生在表单被重置之后。您应该在订阅回调中重置表单。


推荐阅读