reactjs - Rxjs observable 被订阅了两次
问题描述
我从 rxjs 库开始,尝试向 API REST 发出请求。我得到的问题是里面的代码subscribe
被执行了两次,但只被调用了一次
该observable
方法,observable
从一个promise
post(url, body): Observable<Response> {
return from(fetch(url, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json;charset=UTF-8'
}
}))
}
然后,我用来读取流值的代码是:(我已经检查过,它只被调用一次)
doLogin(){
var creds={
"email":"user@gmail.com",
"password":"user"
}
var stream$ =this.httpService.post("http://localhost:8080/api/login",creds)
stream$.subscribe(x=>console.log(x))
}
我在导航器控制台中看到的console.log()
结果是 2 和 fetch 响应的结果
解决方案
我认为在订阅函数中实际发生的是,您定义当您从流中接收到新值时要做什么。这意味着 subscribe 实际上并没有被执行两次,而是两次接收一个值。
推荐阅读
- mysql - 根据连接表中的一种关系获取结果
- sql-server - 限制 SQL 存储过程参数中的位数
- asp.net-mvc - 如何将值从表中的按钮传递到 MVC 中的另一个视图?
- c# - 如果在运行子窗体窗口时单击父窗体会冻结,直到关闭子窗体
- php - 如何通过php,swift将服务器上的图像显示到iOS设备
- 3d - 在运行时导入另一个纹理(使用 .glb 格式的三个.js)
- python - Python:如何以高效的方式搜索大数组?
- kubernetes - Kubernetes Helm:如何在 pod 定义中传递依赖服务的外部 IP?
- xaml - uwp NavigationView 控件标题栏
- javascript - Vue JS 在使用 v-for 渲染的单个项目上切换类