javascript angular4 文档和窗口未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46340374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:36:30  来源:igfitidea点击:

angular4 document and window are undefined

javascriptangularwebpack.net-core

提问by fattikus

I am using dot net core with angular 4 and webpack config.

我正在使用带有 angular 4 和 webpack 配置的 dot net core。

When I am trying to get the window or document in a component or service, I am getting this error:

当我尝试在组件或服务中获取窗口或文档时,出现此错误:

ReferenceError: document is not defined

ReferenceError: window is not defined

参考错误:文档未定义

参考错误:窗口未定义

Here are the errors i am getting:

以下是我收到的错误:

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)

I am still new to the webpack stuff, anyone know how i can fix this? I need the window to handle when a window is resizing.

我还是 webpack 的新手,有人知道我该如何解决这个问题吗?当窗口调整大小时,我需要处理窗口。

EDIT...

编辑...

I managed to get this fixed by removing the pre render from the index.cshtml

我设法通过从 index.cshtml 中删除预渲染来解决这个问题

i changed it from this:

我从这个改变了它:

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

to this:

对此:

<app>Loading...</app>

but now obviously pre rendering on server side won't be happening :/ thus it will slow the app boot up time, any ideas how I can fix this without loosing server side pre rendering?

但是现在显然不会在服务器端进行预渲染:/因此它会减慢应用程序的启动时间,有什么想法可以在不丢失服务器端预渲染的情况下解决这个问题吗?

回答by Anh Nguyen

If you're using server-side rendering, you should remove all code using windowor documentthat run in node because node doesn't have these variables (node only have global).

如果您使用服务器端渲染,您应该删除所有使用windowdocument在节点中运行的代码,因为节点没有这些变量(节点只有global)。

If you still want to use windowor documentin node env, you can try to use jsdom (https://github.com/tmpvar/jsdom).

如果你仍然想使用windowdocument在 node env 中,你可以尝试使用 jsdom ( https://github.com/tmpvar/jsdom)。

回答by G?khan Kurt

If you want to use AOT, use dependency injection to mount window into your components. In short, write a service that can provide the window object:

如果您想使用 AOT,请使用依赖注入将窗口挂载到您的组件中。总之,写一个可以提供window对象的服务:

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

function getWindow (): any {
    return window;
}

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

More information here.

更多信息在这里

回答by Touqeer Shafi

Well i'm using angular 4 application and inject the window object using:

好吧,我正在使用 angular 4 应用程序并使用以下方法注入窗口对象:

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

在组件中 constructor( @Inject('Window') private window: Window) { }

and In module: providers: [{ provide: 'Window', useValue: window }]

并在模块中: providers: [{ provide: 'Window', useValue: window }]

and then in the component function i used it like: this.window

然后在组件函数中我像这样使用它: this.window

回答by Milad

If you want a quick fix : put this code at the top of your typescript file :

如果您想快速修复:将此代码放在打字稿文件的顶部:

 declare var window;
 declare var document;


But if you wanna do it properly :

但如果你想正确地做到这一点:

 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){}

inside your module :

在您的模块内:

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

This way you can override window and document in your tests and anywhere else.

通过这种方式,您可以在测试和其他任何地方覆盖窗口和文档。

回答by Rabbani

In Server Side JavaScript is running in Node Environment which does not have window or document object. Window & Document object works when your javascript code executes in Browser Environment. So make sure window or document object related code does not execute on Server Side

在服务器端,JavaScript 运行在没有窗口或文档对象的节点环境中。当您的 javascript 代码在浏览器环境中执行时,Window & Document 对象会起作用。所以请确保窗口或文档对象相关代码不在服务器端执行

You may use node-jsdom(https://www.npmjs.com/package/node-jsdom) if you really need to use window or document object. Just install

如果您确实需要使用 window 或 document 对象,则可以使用node-jsdom( https://www.npmjs.com/package/node-jsdom)。只需安装

$ npm install node-jsdom 

Here(https://github.com/darrylwest/node-jsdom) you will get help on node-jsdom

在这里https://github.com/darrylwest/node-jsdom)您将获得有关 node-jsdom 的帮助

回答by cahit beyaz

wrap your code which depends on window like below

包装取决于窗口的代码,如下所示

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

回答by user8335505

Place your window. related code inside componentDidMount function.

放置你的窗户。componentDidMount 函数内的相关代码。

回答by Mark Macneil Bikeio

In Index.htmlor Index.cshtml

Index.htmlIndex.cshtml 中

Change From

更改自

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

To

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

If you are using angular4 in aspnetcore, It should work fine

如果您在 aspnetcore 中使用 angular4,它应该可以正常工作