使用可观察的。有人可以向我解释这段代码是如何工作的吗
Using observable. Can someone explain to me how this code works
public SavePatientEducationDetails(patientEducation: any): Observable<any> {
return new Observable<any>(obs => {
this.http.post(environment.API.PATIENT_FAMILLY_EDUCATION + "?isNew=true", patientEducation).subscribe(res => {
this.response = Object.assign(res);
setTimeout(() => {
obs.next(this.response);
obs.complete();
}, 500);
}, err => {
console.log(err);
});
})
}
嗯,一开始使用 observable 的实现是错误的。
在这段代码中,您首先创建一个新的可观察对象:
new Observable<any>(obs => {});
在这个 observable 中,您发出了一个 http post 请求(可能是为了保存一些数据)并订阅它以获取其响应值:
new Observable<any>(obs => {
this.http.post(environment.API.PATIENT_FAMILLY_EDUCATION + "?isNew=true", patientEducation).subscribe(res => {});
});
在订阅中,您使用 this.response = Object.assign(res);
将响应值复制到新对象
最后,在 500 毫秒后(感谢 setTimeOut),您使用 obs.next()
发出响应并使用(显然)obs.complete()
方法完成可观察。
所有这些代码所做的只是向 post 请求添加 500 毫秒, 这已经是一个可观察的 ,因此将请求包装在一个新的可观察的中是没有用的。
对我来说,这样做会得到完全相同的结果:
public SavePatientEducationDetails(patientEducation: any): Observable<any> {
return this.http.post(environment.API.PATIENT_FAMILLY_EDUCATION + "?isNew=true", patientEducation);
}
也许你能说出这段代码的最初目的是什么。
public SavePatientEducationDetails(patientEducation: any): Observable<any> {
return new Observable<any>(obs => {
this.http.post(environment.API.PATIENT_FAMILLY_EDUCATION + "?isNew=true", patientEducation).subscribe(res => {
this.response = Object.assign(res);
setTimeout(() => {
obs.next(this.response);
obs.complete();
}, 500);
}, err => {
console.log(err);
});
})
}
嗯,一开始使用 observable 的实现是错误的。
在这段代码中,您首先创建一个新的可观察对象:
new Observable<any>(obs => {});
在这个 observable 中,您发出了一个 http post 请求(可能是为了保存一些数据)并订阅它以获取其响应值:
new Observable<any>(obs => {
this.http.post(environment.API.PATIENT_FAMILLY_EDUCATION + "?isNew=true", patientEducation).subscribe(res => {});
});
在订阅中,您使用 this.response = Object.assign(res);
将响应值复制到新对象
最后,在 500 毫秒后(感谢 setTimeOut),您使用 obs.next()
发出响应并使用(显然)obs.complete()
方法完成可观察。
所有这些代码所做的只是向 post 请求添加 500 毫秒, 这已经是一个可观察的 ,因此将请求包装在一个新的可观察的中是没有用的。
对我来说,这样做会得到完全相同的结果:
public SavePatientEducationDetails(patientEducation: any): Observable<any> {
return this.http.post(environment.API.PATIENT_FAMILLY_EDUCATION + "?isNew=true", patientEducation);
}
也许你能说出这段代码的最初目的是什么。