【问题标题】:how to implement window.open kind of functionality in Angular 4如何在 Angular 4 中实现 window.open 类型的功能
【发布时间】:2018-10-21 10:00:16
【问题描述】:

您如何在 Angular 4 中实现 window.open() 类型的功能?

function open(){
    var URL = "file:///C:\data2.pdf";

    window.open(URL, null);
}

我收到以下错误消息:

无法打开本地文件 - Chrome:不允许加载本地资源。

如果 Angular 4 中有 window.open() 的替代品,请告诉我。

【问题讨论】:

  • 问题不在于window.open(...),而在于您尝试打​​开的 URL。在 Chrome 中使用file:// 打开本地文件存在安全问题。
  • 我想在新的弹出窗口中打开这个文件。
  • 想在新的弹出窗口中打开,这将在新标签中打开 window.location.href="google.com";它对我不起作用

标签: angular


【解决方案1】:

您应该使用网络服务器。浏览器不允许通过 JavaScript 获取客户端本地文件。示例:

var url = '//localhost:3000/data2.pdf';
window.open(url);

这里的网络服务器地址为localhost,端口为3000。作为网络服务器可以是例如Node JS、Apache等。

【讨论】:

  • 同样的问题无法打开文件。不允许加载本地资源:file:///C:/docstore/doc7.1.pdf
  • 您可以在浏览器中手动打开文件,但您不能通过浏览器JavaScript,因为它不安全。您必须使用 HTTP 而不是 FILE。请阅读有关网络、网络服务器如何工作以及如何处理请求的信息。
【解决方案2】:

您必须在 Angular 项目的资产中引入该文件。要访问该文件,您需要引入“assets/file2.pdf”。

window.open('assets/file2.pdf');

不要使用绝对路径,因为如果部署在子目录中不起作用。

【讨论】:

    【解决方案3】:

    你应该使用Router.navigate Angular 方法:

    import { Router } from '@angular/router';
        
    constructor(
       private router: Router
    ) {}
        
    open(){
       var URL = "file:///C:\data2.pdf";
       this.router.navigate(URL);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 1970-01-01
      • 2011-10-16
      • 1970-01-01
      • 2016-11-20
      • 2018-07-08
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多