【发布时间】: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