【发布时间】:2021-03-09 14:17:36
【问题描述】:
所以,我一直在尝试重定向 URL 并在新选项卡中打开它,但我无法做到。
我有一个 API 会向我返回一个纯文本,它以 BLOB 对象的形式出现,但实际上,它只是一个 URL。我需要在新标签页中打开该 URL。
这是我要开始工作的代码:
this.printingService.getCvUrl(options).subscribe(
url => {
const downloadURL = window.URL.createObjectURL(url);
window.open(downloadURL, '_blank');
}
);
它调用getCvUrl方法,就是这样:
getCvUrl(options: { remoteUrl: string, paperHeight?: string, paperWidth?: string }): Observable<any> {
const user = this.authenticationService.getCurrentUser();
const PRINT_SERVICE = `/api/users/${user.id}/syncMyCV`;
const CV_SERVICE = 'https://cv.url/template/ce';
const formData = new FormData();
formData.append('remoteURL', CV_SERVICE + options.remoteUrl);
formData.append('paperHeight', options.paperHeight);
formData.append('paperWidth', options.paperWidth);
const token = this.authenticationService.getToken();
return this.http.post(
PRINT_SERVICE,
formData,
{
headers: {
'Anonymous': 'undefined',
'accept': '*/*',
'Authorization': token
},
responseType: 'blob'
}
).pipe(catchError(err => {
this.errorService.handleError(err);
return observableOf(null);
}));
}
作为回应,这目前正在为我打开一个新标签,其中包含 URL 的文本作为内容,但不在浏览器的 URL 字段中。
我已经尝试了所有这些方法:
首先我尝试使用路由器导航,但当然,它不起作用,因为我试图打开一个外部 URL。
this.printingService.getCvUrl(options).subscribe(
url => this.router.navigate([url])
);
然后,看了一些问题,我尝试修改窗口位置的href属性。也没有用
this.printingService.getCvUrl(options).subscribe(
url => window.location.href = url
);
然后,在另一个答案之后,我改变了窗口打开方法,它打开了一个新选项卡,但是给了我一个 404 错误
this.printingService.getCvUrl(options).subscribe(
url => window.open(url, '_blank')
);
查看后,我意识到我正在尝试重定向一个 blob 对象,就好像它是一个 URL 字符串一样,因此需要进行一些转换。然后我尝试使用在我正在使用的同一服务中创建的方法。
this.printingService.getCvUrl(options).subscribe(
url => {
this.printingService.view(url);
}
);
然后调用打印服务中的view()方法,实现如下:
view(data: ArrayBuffer, filename = 'resume.pdf') {
if (!!data) {
const blob = new Blob([data], {type: 'application/pdf'});
const downloadURL = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadURL;
link.download = filename;
link.click();
}
}
但问题是这个方法下载了一个pdf,但它甚至不是我想要的,所以我决定从那个方法中获取我需要的东西,并对其进行调整。然后我得到了上面的当前解决方案,它也不起作用:
this.printingService.getCvUrl(options).subscribe(
url => {
const downloadURL = window.URL.createObjectURL(url);
window.open(downloadURL, '_blank');
}
);
到目前为止,我已经没有什么想法了。有没有人有我没有尝试过的其他方法?
使用公认答案的解决方案:
在 getCvUrl 方法中,我更改了这一行:
responseType: 'blob'
通过这个:
responseType: 'text'
因为来自 API 的答案将始终是文本/纯文本响应。最终代码如下所示:
this.printingService.getCvUrl(options).subscribe(
url => {
const downloadLink = document.createElement('a');
downloadLink.href = url;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
);
【问题讨论】:
-
删除这一行
link.download = filename;设置download属性将下载文件而不是在新标签中打开 -
感谢@Prabh,正如您在上次更新的 sn-p 中看到的那样,我没有使用它
标签: angular typescript url redirect blob