注销后我必须退订对主题的订阅?我的用户实际上是我的主题
我有一个authservice,在那里我有一个看起来像这样的登录方法:
user = new Subject<User>();
login(username: string, password: string): Observable<User> {
return this.http
.post<User>('http://localhost:4000/users/authenticate', {
username: username,
password: password,
})
.pipe(
tap((resData) => {
const user = new User(
resData.firstName,
resData.lastName,
resData.username,
resData.id,
resData.token
);
localStorage.setItem('user', JSON.stringify(user));
this.user.next(user);
})
);
}
当我传递用户名和密码时,我在authcomponent中使用此功能:
onSubmit() {
const loginForm = this.loginForm;
if (!loginForm) {
return;
}
const username = this.loginForm.value.username;
const password = this.loginForm.value.password;
this.authService.login(username, password).subscribe({
next: () => this.router.navigate(['/monthly-deposits']),
error: (error) => {
if (!!error.error.message) {
this.error = error.error.message;
}
},
});
this.loginForm.reset();
}
我使用标题中的按钮登录,然后从我的authservice:
logout() {
this.user.next(null);
this.router.navigate(['/login']);
localStorage.removeItem('user');
}
如何删除订阅,因为这意味着内存泄漏。 感谢您的注意。我期待您的答复。
I have an authService and in there I have a login method that looks like that:
user = new Subject<User>();
login(username: string, password: string): Observable<User> {
return this.http
.post<User>('http://localhost:4000/users/authenticate', {
username: username,
password: password,
})
.pipe(
tap((resData) => {
const user = new User(
resData.firstName,
resData.lastName,
resData.username,
resData.id,
resData.token
);
localStorage.setItem('user', JSON.stringify(user));
this.user.next(user);
})
);
}
I use this function in my AuthComponent when I pass my username and password:
onSubmit() {
const loginForm = this.loginForm;
if (!loginForm) {
return;
}
const username = this.loginForm.value.username;
const password = this.loginForm.value.password;
this.authService.login(username, password).subscribe({
next: () => this.router.navigate(['/monthly-deposits']),
error: (error) => {
if (!!error.error.message) {
this.error = error.error.message;
}
},
});
this.loginForm.reset();
}
I use a button in my header to logout and I call a function from my authService:
logout() {
this.user.next(null);
this.router.navigate(['/login']);
localStorage.removeItem('user');
}
How can I remove the subscription, because it means memory leak.
Thanks for your attention. I’m looking forward to your reply.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如何使用管道(拿(1))进行这样的登录订阅。
然后,订阅应在此之后仅在关闭时运行一次。
How about making the login subscription like this, with pipe(take(1)).
Then the subscription should only run once at be closed after that.