【问题标题】:Why does document.open send me to a blank page?为什么 document.open 将我发送到空白页面?
【发布时间】:2020-04-30 11:40:27
【问题描述】:

我想在我的 Angular 8 SPA 的新选项卡中打开一个外部 URL。

Answers to other questions 建议您可以使用window.open(url, "_blank") 来实现这一点,这对我有用,但我正在寻找可以进行单元测试的东西。

基于an answer to a different question,我尝试注入Document 并像这样调用document.open(url, "_blank")

import { Component, OnInit, Input, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";

@Component( ........ )
export class MyClass implements OnInit {

  private externalLink = "https://bbc.co.uk";

  constructor(@Inject(DOCUMENT) private readonly document: Document) { }

  ngOnInit() {
  }

  public navigate() {
    this.document.open(this.externalLink, "_blank");
  }
}

但是,当它运行时,屏幕立即变白,没有其他反应。没有错误记录到控制台,并且在方法中放置断点表明据我所知文档已正确注入。

如果这无法解决,我很想围绕window.open() 包装一个服务并注入它。

【问题讨论】:

  • window.open 包装在一个可以被模拟和监视的服务中是要走的路,IMO。

标签: angular typescript angular8


【解决方案1】:

在没有给出其他答案的情况下,我按照我在问题中的建议做了。我在window.open 周围包裹了一个小服务,如下所示:

import { Injectable } from "@angular/core";

@Injectable({
  providedIn: "root"
})
export class NewTabService {

  constructor() { }

  public open(url: string, newTab: boolean = false) {
    if (newTab) {
      window.open(url, "_blank");
      return;
    }

    window.location.href = url;
  }
}

【讨论】:

    【解决方案2】:

    使用此代码

    window.open(this.externalLink, "_blank");
    

    而不是

    this.document.open(this.externalLink, "_blank");
    

    希望这会有所帮助!!!

    猜你喜欢
    • 2017-10-28
    • 1970-01-01
    • 2014-06-05
    • 2022-04-14
    • 2011-01-12
    • 2020-04-25
    • 1970-01-01
    • 2021-12-01
    相关资源
    最近更新 更多