RxJS 6中如何条件触发二次HTTP POST请求?
Fixing Conditional Second HTTP Request in RxJS 6
Hey there! Let's get this sorted out. The core issue with your current code is that map can't handle asynchronous operations (like that second POST request) — it's only meant for synchronous transformations. Instead, we'll use switchMap, which lets us return a new Observable when we need to run async logic, while falling back to a simple synchronous value otherwise.
Here's the revised implementation, with clear explanations:
import { Observable, of, switchMap, map, catchError } from 'rxjs'; export class BasePortalDetailsManagerService { updateCertificate(file: File): Observable<IUploadProgress> { return this._azureBlobStorage .uploadCertificateToBlobStorage2(file, this.portalKey) .pipe( switchMap(fileProgress => { // Handle the 100% completion case with a second POST if (fileProgress.Progress === 100) { // Replace this with your actual second HTTP POST request logic return this.sendUploadConfirmation(fileProgress.FilePath).pipe( // When the POST succeeds, return the final progress object map(() => ({ filename: fileProgress.FilePath, progress: fileProgress.Progress // Which is 100% here })), // Optional: Gracefully handle errors from the second request catchError(error => { console.error('Upload confirmation failed:', error); // You can return an error-aware object (extend IUploadProgress if needed) return of({ filename: fileProgress.FilePath, progress: fileProgress.Progress, error: 'Failed to confirm upload' }); }) ); } // For partial progress, just return the current state synchronously else { return of({ filename: fileProgress.FilePath, progress: fileProgress.Progress }); } }) ); } // Replace this with your actual second POST method private sendUploadConfirmation(filename: string): Observable<any> { // Example real implementation: // return this.http.post('/api/certificates/confirm', { filename, portalKey: this.portalKey }); return of({ success: true }); // Placeholder for your actual HTTP call } }
Key Changes Explained:
switchMapinstead ofmap: This operator lets us branch logic into either an async Observable (the second POST request) or a synchronous Observable (created withof()for partial progress updates).- Clean logic separation: We explicitly split the 100% completion case (with async work) from partial progress (simple value emission), making the code easier to read and maintain.
- Error handling: Added
catchErrorto handle failures in the second POST — adjust this to match your app's error reporting or recovery needs. - Type consistency: All code paths return an
Observable<IUploadProgress>, so components subscribing toupdateCertificatewill receive consistent data structures.
If you need to pass additional metadata (like blob URLs or upload IDs) from the initial upload to the second request, just include that in the sendUploadConfirmation call.
内容的提问来源于stack exchange,提问作者tony09uk
相关产品推荐
相关产品推荐

