【问题标题】:Angular: Pass variables to window.open();Angular:将变量传递给 window.open();
【发布时间】:2018-07-30 20:17:53
【问题描述】:

我想在 Angular 中打开一个根本没有任何功能的新选项卡。它只是显示数据供用户打印的选项卡。我的问题是,在主应用程序中我调用来获取数据,但是当我打开新选项卡时,变量不保存来自主应用程序的数据。变量被重置,就好像它是 Angular 应用程序的新实例一样。

我通过执行以下操作创建了一个新选项卡:

window.open('#/print-report');

然后在我的应用模块中,上面的路由打开 PrintReportComponent:

{ path: 'print-report', component: PrintReportComponent},

但是在新选项卡中,我的程序中的每个变量都会在应用程序启动时重置为其默认值。如何将任何变量“保存”或“传递”到这个新选项卡?

【问题讨论】:

  • 使用 localStorage 保存域上的值。

标签: angular


【解决方案1】:

你可以试试这样的:

打印报告:

  /**
   * Method is used to print report.
   * @param response - html response.
   */
  printReport(response) {

    let data = response;

    let Pagelink = "about:blank";

    let pwa = window.open(Pagelink, "_new");

    if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {

      alert('Pop-up!', 'Please disable your Pop-up blocker and try again.', 'warning');

    }

    pwa.document.open();

    pwa.document.write(data);

    pwa.print();

  }

下载报告:

    /**
     * Method is use to download file.
     * @param data - Array Buffer data
     * @param type - type of the document.
     */
    downLoadFile(data: any, type: string) {
        var blob = new Blob([data], { type: type.toString() });
        var url = window.URL.createObjectURL(blob);
        window.open(url);
    }

【讨论】:

  • 是否有可能以某种方式将 css 库添加到该新页面中?
【解决方案2】:

尝试使用让您获取数据的服务,然后确保通过 url 中的 id 识别您的数据,然后您可以在 ngOnInit 的新选项卡组件中执行此操作:

this.activatedRoute.params.subscribe((param: any) => {
            this.functionThatGivesYouData(this.activatedRoute.snapshot.params.id);
        });

所以现在您可以通过 id 向相同数据发出新请求。否则,如果您持有机密信息,则应使用不安全的本地存储。

【讨论】:

    【解决方案3】:

    正如@trichetriche 所评论的那样,只需使用本地存储

    【讨论】:

    • 但是这种方式需要存储数据
    • 作为我给出的答案,您可以直接将数据传递给方法进行打印和下载,无需使用本地存储
    猜你喜欢
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多