javascript - 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();
}
解决方案
订阅是异步的,这意味着它发生在表单被重置之后。您应该在订阅回调中重置表单。
推荐阅读
- c++ - Qt JSON – 从子项查询
- react-native - React Native Picker 组件:如何设置插入符号的样式(右侧的小三角形)?
- android - kotlin android 的 gRPC:导入“google/protobuf/wrappers.proto”不起作用
- javascript - 如何使用 Request-Promise 将一个 API 的响应作为请求参数传递给另一个 API
- angular - 如何强制 Angular App 获取最新的 dist
- symfony - 在symfony 4中将树枝数据传递给vue js
- php - 循环遍历具有数组值的会话变量
- vue.js - 路由进入后未加载Vue Child
- r - 使用 R 通过 API 更新 Google Tag Manager 容器:invalidArgument 错误
- typescript - Visual Studio 代码禁用对象解构的代码格式