Angular 角度4非零参考误差
我试图在页面启动时打开一个新页面,但我一直收到一个错误消息 引用错误:未定义窗口 我最近才开始使用TypeScript和Angular4,所以我不确定这两个问题到底属于哪一个Angular 角度4非零参考误差,angular,typescript,Angular,Typescript,我试图在页面启动时打开一个新页面,但我一直收到一个错误消息 引用错误:未定义窗口 我最近才开始使用TypeScript和Angular4,所以我不确定这两个问题到底属于哪一个 export class HomeComponent implements OnInit { testCall: Window; constructor() { this.testCall = new Window(); this.testCall.open( "https://static
export class HomeComponent implements OnInit {
testCall: Window;
constructor() {
this.testCall = new Window();
this.testCall.open(
"https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg");
}
ngOnInit(): void {
console.log("function read");
window.open("https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg");
}
即使我在OnInit()
中使用this.testCall.open
,我也只会在open
方法上得到一个引用错误
我知道当第一页打开时,这是一个简单的页面打开,但是已经一个星期了,我真的不知道如何在typescript/angular4设置中做到这一点。删除这一行
this.testCall = new Window();
window
在JS中是一个全局变量,只需调用window.open('url')
就可以打开一个新窗口 是否尝试在包含HomeComponent的文件中声明窗口
对象?。如果不是,尝试将其声明为
declare var window: any;
在文件顶部(导入后)
TypeScript不知道Windows,因为我们不提供任何有关该窗口的键入信息。在这种情况下,我们可以声明它们来告诉typescript编译器全局名称空间中的窗口引用不是源于typescript文件
阅读有关此场景的更多信息好的,显然服务器上不存在窗口,这就是为什么当我尝试将“window.open”放在那里时,ngOnInit()和constructor()会抛出错误的原因
这对我来说非常有效。您需要删除该行。如果消息保留,那么你没有删除它。当然我删除了那行。但现在它给了我“TypeError:无法读取未定义的属性‘open’”真的很抱歉给您带来麻烦。请阅读我的答案。我已经发布了你的解决方案,有两次你证明你没有读过。
import { Component, PLATFORM_ID, Inject, OnInit } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
export class HomeComponent {
submitted: boolean = false;
constructor(@Inject(PLATFORM_ID) private platformId: Object) {
}
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
window.open("URL");
}
}
}