确定subscribe()中的顺序



我在我的component.ts文件中有一个函数。我要做的是确保uploadFile()的操作在this.isModalOpen=false,this.form.reset()this.list.get()执行之前完成。我的代码工作得很好,但我想这样做,以避免未来潜在的问题。如果有人能提出一个解决方案,并解释一下背后的逻辑,我会很感激的。

save() {
if (this.form.invalid) {
return;
}

if(this.selectedCandidate.id){
this.candidateService.update(this.selectedCandidate.id, this.form.value).subscribe(()=>{
if(this.form.get('file').value){
this.uploadFile(this.selectedCandidate.id);
}
this.isModalOpen=false; 
this.form.reset(); 
this.list.get(); });
}
else{
this.candidateService.create(this.form.value).subscribe((candidateCreate)=>{
if(this.form.get('file').value){
this.uploadFile(candidateCreate.id);
}
this.isModalOpen=false; 
this.form.reset(); 
this.list.get();
});
}
}

uploadFile()只是一个上传pdf文件的函数。

uploadFile(id:string){
const formData = new FormData();
var SERVER_URL =  `https://localhost:44310/api/app/cv/${id}/upload-cv`;
formData.append('file', this.form.get('file').value);
this.httpClient.post<any>(SERVER_URL,formData).subscribe((res) => console.log(res), (err) => console.log(err));
}

你能改变你的上载文件函数返回可观察对象吗?如果您需要捕获错误,请连接一个catchError管道。

uploadFile(id:string){
const formData = new FormData();
var SERVER_URL =  `https://localhost:44310/api/app/cv/${id}/upload-cv`;
formData.append('file', this.form.get('file').value);
return this.httpClient.post<any>(SERVER_URL,formData)
}
this.candidateService.create(this.form.value).subscribe((candidateCreate)=>{
if(this.form.get('file').value){
this.uploadFile(candidateCreate.id)
.subscribe(() => this.isModelOpen=false);
}
else {
this.isModalOpen=false; 
this.form.reset(); 
this.list.get();
}
});

如果你让uploadFile方法返回一个可观察对象:

uploadFile(id:string): Observable<any> {
const formData = new FormData();
var SERVER_URL = `https://localhost:44310/api/app/cv/${id}/upload-cv`;
formData.append('file', this.form.get('file').value);
return this.httpClient.post<any>(SERVER_URL, formData);
}

你可以这样做:

save() {
if (this.form.invalid) {
return;
}

operation$ = this.selectedCandidate.id 
? this.candidateService.update(this.selectedCandidate.id, this.form.value)
: this.candidateService.create(this.form.value);
request$ = operation$.pipe(
switchMap(canidate => this.form.get('file').value
? this.uploadFile(candidate.id)
: of(undefined)
)
);
reqeust$.subscribe(() => {
this.isModalOpen = false; 
this.form.reset(); 
this.list.get();
}));
}

这里的想法是使用构建一个单一的可观察对象(request$),它将发出一次你所有的"工作"。就完成了。我们将request$定义为从operation$开始,将其排放到switchMap

传递一个函数返回一个可观察对象到switchMap;该函数返回对uploadFile()的调用,或者返回一个可观察对象,使用of立即发出undefined(表示没有上传文件)。

This "inner observable"被switchMap自动订阅并排放。

现在,我们可以简单地订阅request$,并在工作完成时接收一个发射。因此,subscribe()中的任何内容只会在工作完成后执行。

最新更新