javascript - 如何在switchmap中发送带有条件的嵌套http请求?
问题描述
嗨,我有一个函数,我想发送两个 http 请求,第二个请求只是在第一个请求完成后,我在管道内使用 switchMap,条件基于一个角度形式,我的编辑器显示下一个错误:
Argument of type '(data: Object) => void' is not assignable to parameter of type '(value: Object, index: number) => ObservableInput<any>'.
Type 'void' is not assignable to type 'ObservableInput<any>'.
这是我的功能:
store() {
this.empleadosEmpleadoService.store({
fecha_contratacion: this.empleadoForm.value.fecha_contratacion,
fecha_nacimiento: this.empleadoForm.value.fecha_nacimiento,
curp: this.empleadoForm.value.curp,
rfc: this.empleadoForm.value.rfc,
telefono: this.empleadoForm.value.telefono,
user: {
email: this.empleadoForm.value.email,
username: this.empleadoForm.value.username,
password: this.empleadoForm.value.password,
first_name: this.empleadoForm.value.first_name,
last_name: this.empleadoForm.value.last_name
}
}).pipe(
switchMap(data =>{
if(this.empleadoForm.value.foto){
this.empleadosEmpleadoService.subirFoto(
data['user_id'],
this.empleadoForm.value.foto
)
}
})
).subscribe(async empleado => {
if(empleado) {
this.empleadoForm.reset();
this.empleadoAgregado.emit(empleado);
this.dismissModal();
}
});
}
解决方案
对于 a switchMap
,您需要返回一个 Observable,因为您正在从源切换。由于 source 是一个可观察的流,切换后的输入也应该是一个可观察的流。
假设this.empleadosEmpleadoService.subirFoto
也是网络请求,应该返回一个observable,需要返回给switchMap。
请注意以下两个return
语句:
import { of as observableOf } from 'rxjs';
store() {
this.empleadosEmpleadoService.store({
fecha_contratacion: this.empleadoForm.value.fecha_contratacion,
fecha_nacimiento: this.empleadoForm.value.fecha_nacimiento,
curp: this.empleadoForm.value.curp,
rfc: this.empleadoForm.value.rfc,
telefono: this.empleadoForm.value.telefono,
user: {
email: this.empleadoForm.value.email,
username: this.empleadoForm.value.username,
password: this.empleadoForm.value.password,
first_name: this.empleadoForm.value.first_name,
last_name: this.empleadoForm.value.last_name
}
}).pipe(
switchMap(data =>{
if(this.empleadoForm.value.foto){
// Assuming this.empleadosEmpleadoService.subirFoto returns an Observable
return this.empleadosEmpleadoService.subirFoto(
data['user_id'],
this.empleadoForm.value.foto
)
}
// You must return an observable to a switchMap
return observableOf(data); // Or return whatever you want
})
).subscribe(async empleado => {
if(empleado) {
this.empleadoForm.reset();
this.empleadoAgregado.emit(empleado);
this.dismissModal();
}
});
}
Type 'void' is not assignable to type 'ObservableInput<any>'.
// is complaining that you needed to return an Observable, but you are returning 'void' (not returning anything)
推荐阅读
- excel - 使用来自另一个单元格的颜色名称在一个单元格中设置条件阴影
- c# - C# AES 加密算法转 Python3
- pine-script - PineScript 中是否有计算显示条数的函数?
- wix - 如何使用 Wix msi 选择性地安装 MSI
- css - 用 CSS 绘制一个 div
- javascript - 尝试将 Sequelize 中的两个数据库表与连接器表连接起来
- excel - 如何使用 VBA 从 IE 的下拉列表中选择和选择一个值?
- logging - cakephp ip 地址返回 1 而不是 ip 地址
- javascript - 用于计算的函数不起作用,一条不能长于 2 的蛇?
- flutter - HTTP 调用永远不会颤抖