2016-11-23 46 views
19

打開新的窗口,我試圖打開一個新的窗口,當按鈕用戶點擊如下如何在新標籤頁中angular2

protected assignActity(type: string): void { 
    var window = window.open('/#/link'); 
    this.Service.assignActivity(type).subscribe(res => { 
     window.location = '/#/link/' + res; 
     console.log(res); 
    }) 
    } 

但它拋出一個錯誤,

core.umd.js:3468 TypeError: Cannot read property 'open' of undefined 

請糾正我讓它工作。

+0

'窗口.open('some url');'會工作,但如果你想使用角度通用,你會直接操作窗口。 – Maxime

+0

所以它可能或不可能 – Rhushikesh

+0

我有這個要求,所以如果你有任何解決方法,請建議 – Rhushikesh

回答

33

window變量的原因undefined變量爲您在本地範圍中再次聲明瞭一個名爲window的變量。

根據javascript/typescript的範圍規則,在全局變量被訪問之前,查找局部變量值。 另外當你最初聲明一個變量時,它被設置爲undefined,因此你收到錯誤信息。

因此,所有你需要做的就是簡單地改變變量名在其中捕捉到打開的選項卡的參考

var newWindow = window.open('some_url'); 

然而,這並非是推薦的方法,因爲angular2應用程序可以在各種環境,如運行移動或被呈現的服務器端,其中window對象可能或不可用。更不用說在測試中嘲笑窗口對象是非常困難的

相反,您可以將window對象包裝在服務中,並將該服務注入到組件中。這樣,您就可以根據環境的簡單替代服務實現,採用依賴注入

服務文件

@Injectable() 
export class WindowRef { 
    constructor() {} 

    getNativeWindow() { 
     return window; 
    } 
} 

組件文件

@Component({ 
    selector : 'demo', 
    template : '<div> Demo </div>' 
}) 
class DemoComponent { 

    nativeWindow: any 
    constructor(private winRef: WindowRef) { 
     this.nativeWindow = winRef.getNativeWindow(); 
    } 

    protected assignActity(type: string): void { 
     var newWindow = this.nativeWindow.open('/#/link'); 
     this.Service.assignActivity(type).subscribe(res => { 

     newWindow.location = '/#/link/' + res; 
     console.log(res); 
    }) 
} 
+0

嘿,它的工作感謝..! – Rhushikesh

+0

這個工程!謝謝......但是你能解釋一下這部分嗎? this.Service.assignActivity(type).subscribe()... – normalUser

+4

@normalUser是從原始問題複製的代碼 – ChrisG