Angular打开新标签页加载文件时路由一直跳转首页如何解决
Angular 新标签页打开Blob文件被重定向到首页解决方案
问题根因
- 直接传入Blob对象调用
window.open()不符合API入参要求,未生成合法的访问地址,浏览器路径解析失败后触发Angular路由通配符规则,重定向到首页 - a标签未阻止默认点击行为,额外触发了路由跳转逻辑
修正步骤
1. 调整TypeScript逻辑
openFile(myFile: any){ this.myService.getFile.subscribe((res: any) => { // 若请求时已经指定responseType为blob,可省略new Blob封装步骤 const file = new Blob([res], { type: 'application/pdf' }); // 生成合法的Blob临时访问地址 const fileUrl = URL.createObjectURL(file); // 指定_blank参数打开新标签页 const newWindow = window.open(fileUrl, '_blank'); // 页面加载完成后释放临时URL,避免内存泄漏 if (newWindow) { newWindow.onload = () => URL.revokeObjectURL(fileUrl); } }) }
额外优化:对应服务的文件请求方法直接指定响应类型为blob,避免二进制流解析错误:
// service 层代码示例 getFile(fileId: string) { return this.http.get(`/api/file/${fileId}`, { responseType: 'blob' }); }
2. 调整HTML模板
阻止a标签默认跳转行为,避免多余的路由触发:
<a (click)="openFile(element); $event.preventDefault()" href="javascript:void(0)"> 打开文件 </a>
内容的提问来源于stack exchange,提问作者shakz
相关产品推荐
相关产品推荐

