Reputation: 1927
After doing some experiments, I post the code without my changes, to find the best practice: I have a function (in service) that subscribes to a result as a BLOB and save it as a content of a file to the local file system - FileSaver.saveAs(result, );:
printAsPDF()
{
if (<some validator fails>)
{
return;
}
let htmlContent = "<html><body>" + <some html content> +"</body></html>";
//this.GetByteArrayForPDF returns Observable<any> (actually observable of a blob)
this.GetByteArrayForPDF(htmlContent).subscribe(result =>
{
FileSaver.saveAs(result, <file name>);
}, error => console.log(error));
}
Now, I want that function printAsPDF to return also an observable which indicate whether the save action succeeded or not. Currently, the call to that function is being executed from a component:
this.<service name>.printAsPDF();
I want that component function to subscribe to the observable and check if the saving succeeded or not. How can I do it taking into consideration that the call to printAsPDF should get an observable(true) depending if FileSaver.saveAs(result, ) was called
Upvotes: 2
Views: 445
Reputation: 61369
Change your subscribe
to a map
(you'll need to subscribe in your component to make the observable hot of course). You can move the error handler to your component or put it in a catch
method.
return this.GetByteArrayForPDF(htmlContent)
.map(result =>
{
FileSaver.saveAs(result, <file name>);
return true;
})
.catch(error => {
console.log(error);
return Observable.of(false);
});
or using pipeable operators (RxJS 5.5+):
import { catchError, map } from 'rxjs/operators';
return this.GetByteArrayForPDF(htmlContent).pipe(
map(result =>
{
FileSaver.saveAs(result, <file name>);
return true;
}),
catchError(error => {
console.log(error);
return Observable.of(false);
}));
Upvotes: 1