繁体   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