Angular 2从API下载PDF并在View中显示 [英] Angular 2 download PDF from API and Display it in View

查看:67
本文介绍了Angular 2从API下载PDF并在View中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Angular 2 Beta.我想知道如何从API下载PDF文件并在我的视图中显示它吗?我尝试使用以下方法发出请求:

I'm learning Angular 2 Beta. I wonder how to download the PDF file from the API and display it in my view? I've tried to make a request using the following:

    var headers = new Headers();
    headers.append('Accept', 'application/pdf');
    var options = new ResponseOptions({
        headers: headers
    });
    var response = new Response(options);
    this.http.get(this.setUrl(endpoint), response).map(res => res.arrayBuffer()).subscribe(r=>{
       console.log(r);
    })

  • 请注意,我仅使用console.log来查看r
  • 的值

    • Please note that I only use the console.log to see the value of r
    • 但是我总是收到以下异常消息:

      But I always get the following exception message:

      "arrayBuffer()"方法未在Response超类上实现

      "arrayBuffer()" method not implemented on Response superclass

      是因为该方法尚未在Angular 2 Beta中准备好吗?还是我犯了任何错误?

      Is it because that method isn't ready yet in Angular 2 Beta? Or is there any mistake that I made?

      任何帮助将不胜感激.非常感谢.

      Any help would be appreciated. Thank you very much.

      推荐答案

      实际上,HTTP支持中尚未实现此功能.

      In fact, this feature isn't implemented yet in the HTTP support.

      作为一种解决方法,您需要按如下所述扩展Angular2的BrowserXhr类,以在基础xhr对象上将responseType设置为blob:

      As a workaround, you need to extend the BrowserXhr class of Angular2 as described below to set the responseType to blob on the underlying xhr object:

      import {Injectable} from 'angular2/core';
      import {BrowserXhr} from 'angular2/http';
      
      @Injectable()
      export class CustomBrowserXhr extends BrowserXhr {
        constructor() {}
        build(): any {
          let xhr = super.build();
          xhr.responseType = "blob";
          return <any>(xhr);
        }
      }
      

      然后,您需要将响应有效载荷包装到Blob对象中,并使用 FileSaver 库打开下载对话框:

      Then you need to wrap the response payload into a Blob object and use the FileSaver library to open the download dialog:

      downloadFile() {
        this.http.get(
          'https://mapapi.apispark.net/v1/images/Granizo.pdf').subscribe(
            (response) => {
              var mediaType = 'application/pdf';
              var blob = new Blob([response._body], {type: mediaType});
              var filename = 'test.pdf';
              saveAs(blob, filename);
            });
      }
      

      FileSaver 库必须包含在HTML文件中:

      The FileSaver library must be included into your HTML file:

      <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
      

      请参阅以下代码: http://plnkr.co/edit/tfpS9k2YOO1bMgXBky5Y?p=preview

      不幸的是,这将为所有AJAX请求设置responseType.为了能够设置此属性的值,在XHRConnectionHttp类中还有更多更新要做.

      Unfortunately this will set the responseType for all AJAX requests. To be able to set the value of this property, there are more updates to do in the XHRConnection and Http classes.

      作为参考,请参见以下链接:

      As references see these links:

      • Download pdf file using jquery ajax
      • Receive zip file, angularJs

      修改

      经过更多考虑,我认为您可以利用分层注入器并仅在执行下载的组件级别配置此提供程序:

      After thinking a bit more, I think that you could leverage hierarchical injectors and configure this provider only at the level of the component that executes the download:

      @Component({
        selector: 'download',
        template: '<div (click)="downloadFile() ">Download</div>'
        , providers: [
          provide(CustomBrowserXhr, 
            { useClass: CustomBrowserXhr }
        ]
      })
      export class DownloadComponent {
        @Input()
        filename:string;
      
        constructor(private http:Http) {
        }
      
        downloadFile() {
          this.http.get(
            'https://mapapi.apispark.net/v1/images/'+this.filename).subscribe(
              (response) => {
                var mediaType = 'application/pdf';
                var blob = new Blob([response._body], {type: mediaType});
                var filename = 'test.pdf';
                saveAs(blob, filename);
              });
          }
      }
      

      此替代方法仅适用于此组件(引导应用程序时,请不要忘记删除相应的提供).下载组件可以这样使用:

      This override would only applies for this component (don't forget to remove the corresponding provide when bootstrapping your application). The download component could be used like that:

      @Component({
        selector: 'somecomponent',
        template: `
          <download filename="'Granizo.pdf'"></download>
        `
        , directives: [ DownloadComponent ]
      })
      

      这篇关于Angular 2从API下载PDF并在View中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆