typescript Angular 2 - 点击事件下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40370777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:59:09  来源:igfitidea点击:

Angular 2 - Download File on Click Event

javascriptangulartypescript

提问by jjj

I am unable to find the answer anywhere, hopefully someone can help.

我无法在任何地方找到答案,希望有人可以提供帮助。

I have an Angular2 click event defined in the template, inside the table's cell:

我在模板中定义了一个 Angular2 单击事件,位于表格的单元格内:

<td (click)="click2Download()">fileName.txt</td>

In the typescript component, I need help to define a method click2Download()that would automatically start downloading the fileName.txt to client's browser. Note: file is on the same domain, e.g.:

在打字稿组件中,我需要帮助定义一个方法click2Download(),该方法将自动开始将 fileName.txt 下载到客户端的浏览器。注意:文件在同一个域中,例如:

http://example.com/fileName.txt

Any way of doing this with Angular2?

有没有办法用 Angular2 做到这一点?

回答by spa900

Have you tried: window.location.href = '...';?

你有没有试过:window.location.href = '...';

To force download of files you should use html attribute: <a target="_self" href="somefile.txt" download="somefile.txt">

要强制下载文件,您应该使用 html 属性: <a target="_self" href="somefile.txt" download="somefile.txt">