简体   繁体   English

Angular2:单击事件目标会导致无限循环

[英]Angular2 : click on event target causes an infinite loop

I want to download a csv file from my angular2 website. 我想从我的angular2网站下载一个csv文件。 For this I get data from a json file. 为此,我从json文件中获取数据。 Once the parameters download and href are configurated, I want to simulate a click to launch the download. 配置好参数download和href之后,我想模拟一次单击以启动下载。

However this click cause a infinite loop of download ... How is it possible to resolve this problem and download only one file ? 但是,此单击会导致下载的无限循环...如何解决此问题并仅下载一个文件?

Here my component.html code : 这是我的component.html代码:

<div>
    <a class="csv-template" (click)="downloadCSVTemplate($event)">Dowload File</a>
</div>

My component.ts code : 我的component.ts代码:

downloadCSVTemplate(event) {
let locale = this.navContextSrvc.locale;

this.http
    .get('assets/csv/template_'+ locale +'.json')
    .subscribe(res => {
        event.target.download = 'template_'+ locale +'.csv';
        event.target.href = 'data:text/csv;charset=utf-8,'
        + encodeURIComponent(res._body);
        event.stopPropagation();
        event.target.click(); // causes infinite loop of download
        event.preventDefault();
    });
}

This: 这个:

event.target.click(); // causes infinite loop of download

does not cause an "infinite loop of download", it causes an infinite loop by calling the downloadCSVTemplate over and over. 不会导致“下载无限循环”,而是通过反复调用downloadCSVTemplate导致无限循环。

It's unclear what you are trying to do by calling click() again. 不清楚您要通过再次调用click()来尝试做什么。

The problem was my async call. 问题是我的异步电话。 The download was launched before that my href attribut changed. 在我的href属性更改之前启动了下载。

However, because I choose to download files from my client, I just call the file whithout passing by the async call. 但是,因为我选择从客户端下载文件,所以我只是在没有通过异步调用传递的情况下调用文件。 With this, the download is launched after my changements 有了这个,下载会在我更改后启动

Here the code : 这里的代码:

downloadCSVTemplate(event) {
    let locale = this.navContextSrvc.locale;
    event.target.download = 'template_'+ locale +'.csv';
    event.target.href = 'assets/csv/template_'+ locale +'.csv';
}

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

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