簡體   English   中英

angular4文檔和窗口未定義

[英]angular4 document and window are undefined

我使用dot net core with angular 4和webpack config。

當我試圖在組件或服務中獲取窗口或文檔時,我收到此錯誤:

ReferenceError:未定義文檔

ReferenceError:未定義窗口

以下是我得到的錯誤:

 Microsoft.AspNetCore.NodeServices[0] ERROR { ReferenceError: window is not defined at _window (C:\\gitRepose\\AngularCore\\FM\\FMWebApp\\FootballWebApp\\ClientApp\\dist\\main-server.js:30801:12) 

 Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0] An unhandled exception has occurred: window is not defined ReferenceError: window is not defined at _window (C:\\gitRepose\\AngularCore\\FM\\FMWebApp\\FootballWebApp\\ClientApp\\dist\\main-server.js:30801:12) 

我仍然是webpack的新手,有誰知道我可以解決這個問題? 當窗口調整大小時,我需要窗口來處理。

編輯...

我設法通過從index.cshtml中刪除預渲染來解決這個問題

我改變了這個:

<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>

對此:

<app>Loading...</app>

但現在很明顯在服務器端進行預渲染不會發生:/因此它會減慢應用程序啟動時間,任何想法如何解決這個問題而不會丟失服務器端預渲染?

如果您正在使用服務器端呈現,則應使用在節點中運行的windowdocument刪除所有代碼,因為節點沒有這些變量(節點只有global )。

如果您仍想在節點env中使用windowdocument ,則可以嘗試使用jsdom( https://github.com/tmpvar/jsdom )。

如果要使用AOT,請使用依賴注入將窗口裝入組件。 簡而言之,編寫一個可以提供window對象的服務:

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

function getWindow (): any {
    return window;
}

@Injectable()
export class WindowRefService {
    get nativeWindow (): any {
        return getWindow();
    }
}

更多信息在這里

好吧,我正在使用角度4應用程序並使用以下方法注入窗口對象:

在Component constructor( @Inject('Window') private window: Window) { }

和模塊: providers: [{ provide: 'Window', useValue: window }]

然后在組件函數中我使用它: this.window

如果您想快速修復:將此代碼放在您的打字稿文件的頂部:

 declare var window;
 declare var document;

但如果你想做得恰到好處:

 import { DOCUMENT } from '@angular/platform-browser';
 export const WINDOW           = new InjectionToken( 'WINDOW' );

 @Component()
 export class YourComponent{
          constructor(
              @Inject( WINDOW ) private window,
              @Inject( DOCUMENT ) private document){}

在你的模塊內:

providers       : [
    {
        provide  : WINDOW,
        useValue : window
    }
],

這樣,您可以在測試和其他任何地方覆蓋窗口和文檔。

在服務器端,JavaScript在節點環境中運行,該環境沒有窗口或文檔對象。 當您的JavaScript代碼在瀏覽器環境中執行時,Window&Document對象可以正常工作。 因此,請確保窗口或文檔對象相關的代碼不在服務器端執行

如果確實需要使用窗口或文檔對象,可以使用node-jsdomhttps://www.npmjs.com/package/node-jsdom )。 只需安裝

$ npm install node-jsdom 

在這里https://github.com/darrylwest/node-jsdom )你會得到node-jsdom的幫助

包裝你的代碼依賴於窗口,如下所示

if (typeof window !== 'undefined') {
    // your client-only logic here like below
    alert(window.innerWidth);
}

放置你的窗戶。 componentDidMount函數中的相關代碼。

Index.htmlIndex.cshtml中

改變

<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>

<app asp-ng2-prerender-module="ClientApp/dist/main-server">Loading...</app>

如果你在aspnetcore中使用angular4,它應該工作正常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM