angular - Angular中window.location.href的等价物是什么
问题描述
在我的应用程序中,用户可以从作为 Spring Boot 应用程序的后端以流的形式下载文件,这是后端代码:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody download() throws IOException {
final InputStream fecFile = new FileInputStream(new File("C:\\file.zip"));;
return (os) - > {
readAndWrite(fecFile, os);
};
}
private void readAndWrite(final InputStream is, OutputStream os) throws IOException {
byte[] data = new byte[2048];
int read = 0;
while ((read = is.read(data)) >= 0) {
os.write(data, 0, read);
}
os.flush();
}
在 Angular 内部,我使用以下内容下载文件:
window.location.href = "http://localhost:8080/download"
哪个工作很好,但是我添加了一个基于访问令牌的身份验证,并且我无法将令牌添加到 window.location.href,有没有办法以角度执行此操作,我尝试使用HttpModule但它没有下载文件(它没有'不显示任何响应或错误,即使我的控制器被调用),那么有没有办法使用 jquery 或其他库来实现这一点?
解决方案
您必须创建一个特定的方法(在服务中或直接从组件中,这取决于您,但我更喜欢 SOC 原则,这就是我分开的原因)
在服务部分:
const httpOptions = {
headers: new HttpHeaders({
'Key': key
})
};
getFile(){
return this.http.get("http://localhost:8080/download", httpOptions )
}
稍后在您的组件方面:
constructor(private myService: MyTestServiceService ) { }
downloadFile(data: Response) {
const blob = new Blob([data], { type: 'text/pdf' }); // pdf is an example
const url= window.URL.createObjectURL(blob);
window.open(url);
}
myMethodToCallMyService() {
this.myService.getFile()
.subscribe(
(data) => {
this.downloadFile(data)
},
(error) => {
console.log("Server error");
}
);
}
推荐阅读
- html - 可滚动的 div,其中子项仅在可以显示而不会溢出时才显示
- python - 如何在 Plotly 中使用直方图将所有异常值放入一个 bin 中?
- python - Project Euler 问题 17,Python,我弄错了答案,不知道为什么
- python - PyQT 4 需要帮助来调整屏幕分辨率
- python - 如何让scrapy跟随无效链接?
- azure - ADFv2:如何在设置后删除与 GIT 存储库的连接?
- sql-server - SQL Server Reporting Services 从 SSRS 生成的报告订阅中导出单独的 PDF
- javascript - Firebase 错误:运行 Jest 测试时浏览器不受支持
- php - Kubernetes 命名空间环境标头
- css - 更改 FontAwesome 跨度图标的悬停颜色