【发布时间】:2021-06-13 20:22:22
【问题描述】:
我有一个登录服务组件,它有一个行为主题 _loginEmailId" and the method updateLoginEmailId(email:string)` 来更新它的值,如下所示。
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
}
在登录组件中,我通过传递从响应式表单中捕获的电子邮件 ID 和密码,从 登录服务组件 订阅 login 方法。在这个订阅函数中,收到响应后,我试图通过调用updateLoginEmailId(email:string) 来更新登录服务中的_loginEmailId,以便我可以在另一个组件中使用它。但我无法将this.loginEmail 传递给updateLoginEmailId(email:string)。
当我在subscribe 内记录this.loginEmail 时,它会记录为空,而在订阅之外它会记录正确的值。
我知道,这是因为this 不是指组件。
我见过that=this hack,也没有用。
我该如何解决这个问题。
我的登录组件看起来像这样
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();
}
【问题讨论】:
标签: javascript angular typescript frontend