Angular 2下载带有身份验证的.CSV文件点击事件 [英] Angular 2 download .CSV file click event with authentication

查看:141
本文介绍了Angular 2下载带有身份验证的.CSV文件点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用spring boot后端,而我的api使用服务通过OutputStreamWriter发送数据。我可以使用像这样的点击事件在Angular 2中下载:

I'm using a spring boot backend and my api uses a service to send data via an OutputStreamWriter. I can download this in Angular 2 using a click event like so:

打字稿

results(){
window.location.href='myapicall';
}

HTML

<button (click)="results()"
                    class="btn btn-primary">Export</button>

这很好用;但是,我最近为我的api端点实现了安全性,现在每次尝试拨打电话时都会收到401,因为它没有发送标头。

This works just fine; however, I recently implemented security for my api endpoints and now I am receiving a 401 everytime I try to make the call because it's not sending a header.

我写了一个服务,我可以在控制台中看到结果,但我似乎无法弄清楚如何下载文件。

I wrote a service that I can see the results in the console, but I can't seem to figure out how to download the file.

DownloadFileService

import {Injectable} from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class DownloadFileService {

    headers:Headers;
    bearer: string;
    constructor(public http: Http) {}



    getFile(url:string) {
        this.bearer = 'Bearer '+ localStorage.getItem('currentUser');
        this.headers = new Headers();
        this.headers.append('Authorization', this.bearer);

        return this.http.get(url, {headers: this.headers});
    }



}

我尝试通过blob下载数据,如本文所述:
如何使用Angular2下载文件

I tried downloading the data via a blob as suggested in this post: How do I download a file with Angular2

下载的文件类型为File,内容为:

The file that gets downloaded is of type File and the content is:


回复状态:200确定网址:我的网址

Response with status: 200 OK for URL:my url

它实际上并没有下载数据。

It doesn't actually download the data.

downloadFile(data: any){
        var blob = new Blob([data], { type: 'text/csv' });
        var url= window.URL.createObjectURL(blob);
        window.open(url);
    }



    results(){
        // window.location.href='myapicall';   

         let resultURL =  'myapicall';

        this.downloadfileservice.getFile(resultURL).subscribe(data => this.downloadFile(data)),//console.log(data),
            error => console.log("Error downloading the file."),
            () => console.info("OK");



    }


推荐答案

看起来你只需要解析响应的主体,即

Looks like you just need to parse the body of the response i.e

let parsedResponse = data.text();
this.downloadFile(parsedResponse);

我还建议您使用 FileSaver 即使在2016年下载文件也似乎没有一种标准的方式在浏览器中执行此操作。

Also I would recommend you use FileSaver to download files as even in 2016 there does not seem to be a standard way to do this across browsers.

let blob = new Blob([data], { type: 'text/csv' });
saveAs(blob, "data.txt");

如需更深入的指南,请检查这里

For a more in depth guide check here

这篇关于Angular 2下载带有身份验证的.CSV文件点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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