angular - Angular 服务内的所有身份验证逻辑
问题描述
我想在 auth 服务中移动所有业务逻辑,在组件方面我只想调用该方法因为我的函数都没有返回任何内容,这样可以吗?或者它们会挂起吗?
零件
credentials: Credentials = {
email: 'pacurarudaniel@gmail.com',
password: '123'
}
onLogIn(): void {
this.authService.logIn(this.credentials.email, this.credentials.password);
}
服务
public logIn(email: string, password: string): void {
this.http.post<any>('http://localhost:3100/login', { email, password })
.subscribe(user => {
localStorage.setItem('TOKEN', user.token)
this.router.navigateByUrl('/home');
});
}
解决方案
您的服务方法不需要返回任何东西,它不会挂起。Angular 中的 HttpClient 使用 RxJs 工作,这是一种执行异步代码的方式。
您可以选择订阅(或将订阅返回)组件,而不是让您的组件能够根据需要取消。
如果你想订阅你的组件,你可以tap
用来获取你需要的结果数据。
对我来说,这些方法中的任何一种都是设置代码的完全有效的方法。
推荐阅读
- sharepoint - 如何使用 Sharepoint Rest API 更新 sharepoint 中的多个文档元数据
- elasticsearch - Elasticsearch 从索引中删除文档
- visual-studio - Visual Studio 2019 社区版离线安装程序
- mysql - 关于 SQL 内连接
- twitter-bootstrap - Bootstrap 5 类“me-auto”是什么意思
- mysql - 在查询生成器中使用联接查询时,错误显示为字段列表中的未知列
- kubernetes - 入口 - 如何使用基本 URL 分散注意力?
- css - 如何在css中分三个部分制作对角线边框
- python - Tcl 没有正确安装
- python-3.x - 使用 Python 连接时出现雪花角色错误