简体   繁体   English

从订阅中获得可观察性

[英]get observable from a subscription

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, );:在做了一些实验之后,我发布了没有更改的代码,以找到最佳实践:我有一个函数(在服务中)将结果订阅为 BLOB 并将其作为文件内容保存到本地文件系统 - 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.现在,我希望函数 printAsPDF 也返回一个 observable,指示保存操作是否成功。 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.我希望该组件函数订阅 observable 并检查保存是否成功。 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考虑到调用 printAsPDF 应该得到一个 observable(true) 取决于 FileSaver.saveAs(result, ) 是否被调用,我该怎么做

Change your subscribe to a map (you'll need to subscribe in your component to make the observable hot of course).更改您对mapsubscribe (当然,您需要在组件中订阅才能使可观察对象变热)。 You can move the error handler to your component or put it in a catch method.您可以将错误处理程序移动到您的组件或将其放入catch方法中。

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+):或使用可管道操作符(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);
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM