Can someone help me with creating a function that I can subscribe to, returning:
- an observable containing the result if all operations were successful
- an observable with an empty string in all other scenarios
foo(): void {
this.uploadImage.subscribe(res => console.log('url: ' + res));
}
uploadImage(): Observable<string> {
if (isValid(this.file)) {
this.httpHandler.uploadImage(this.file).subscribe(
(result) => {
if (result) {
this.httpHandler.verifyUpload(result.uploadId).subscribe(
(res) => {
if (res) {
return of(res.url);
} else {
return of('');
}
});
} else {
return of('');
}
}
);
} else {
return of('');
}
}
- I am struggling with adding a proper return statement at the end
- In cases of error, nothing is being returned
- The code feels cluttered, I simply want to return an Observable with an empty string if something goes wrong during the operation
Thank you for your assistance
Edit: updated version based on feedback - now working correctly:
foo(): void {
this.uploadImage().subscribe(res => console.log('url: ' + res));
}
uploadImage(): Observable<string> {
if (isValid(this.file)) {
return of(''):
}
return this.httpHandler.uploadImage(this.file).pipe(
switchMap(result => {
if (result) {
return this.httpHandler.verifyUpload(result.uploadId)
} else {
return of('');
}
}),
map((res: any) => res.verified?.url || ''),
catchError(() => of(''))
);
}