2017-07-03 157 views
0

我想在頁面啓動時打開一個新的頁面,但我不斷收到一個角4 NgOnInitReference錯誤

Reference Error: Window not defined.

我只開始與打字稿及Angular4最近的工作,所以我不這樣確定這個問題真正屬於哪一個。

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"); 
} 

即使我使用this.testCall.openOnInit()裏面,我只得到一個參考錯誤,但在open方法。

我知道這是一個簡單的頁面打開時,第一頁打開,但它已經一個星期了,我真的不知道如何在打字稿/ angular4設置中做到這一點。

回答

0

刪除此行

this.testCall = new Window(); 

window是JS的全局變量,只是打電話window.open('url')應該打開一個新的窗口。

+0

已經嘗試過,沒有工作。窗口未定義。 :( – RoboKy

+0

你需要刪除該行,如果郵件仍然存在,那麼你並沒有刪除它 – trichetriche

+0

當然,我刪除了該行,除了現在它給我「TypeError:無法讀取未定義的屬性」打開「真的很抱歉對於這個問題 – RoboKy

0

您是否嘗試在包含HomeComponent?的文件中聲明window對象。如果不是,請嘗試將其聲明爲;

declare var window: any; 

位於文件頂部(導入後)。

TypeScript不知道窗口,因爲我們沒有提供任何關於該窗口的輸入信息。在這種情況下,我們可以聲明那些告訴打字稿編譯器全局命名空間中的window引用不是源自打字稿文件。

瞭解更多關於此方案here

0

好吧顯然窗口不存在的服務器,這就是爲什麼當我嘗試把「window.open」有

ngOnInit()和構造函數()引發錯誤
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"); 
    } 
} 
} 

這對我來說非常合適。