文章内容

2021/5/11 16:23:18,作 者: 黄兵

Angular Universal window is not defined

最近在使用Angular Universal的时候,有一些代码使用了window,在编译的时候出现错误,具体错误内容:

window is not defined

出现问题的原因:

如果从诸如Node.js之类的服务器呈现应用程序,则可能是由于对Window对象的引用导致此错误。

解决方案:

首先,包装全局Window对象的服务:

windowRef.service.ts

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

function _window(): any {
  return window;
}

@Injectable({
  providedIn: 'root'
})
export class WindowRef {
  get nativeWindow(): any {
    return _window();
  }
}

之后在需要使用到window的地方初始化服务:

import { PLATFORM_ID } from "@angular/core";
import { isPlatformBrowser } from '@angular/common';
import { WindowRef } from './services/windowRef.service';
...
constructor(
 @Inject(PLATFORM_ID) private platformId: any,
 private windowRef: WindowRef
){}
...
if(isPlatformBrowser(this.platformId)) {
  // Use the window reference: this.windowRef
 Eg: this.windowRef.nativeWindow.location.pathname
    this.innerHeight = this.windowRef.nativeWindow.innerHeight;
    this.innerWidth = this.windowRef.nativeWindow.innerWidth;
}

PLATFORM_ID是String对象类型的不透明令牌(Now InjectionToken),此令牌可帮助DI获取当前平台(浏览器/服务器)。

isPlatformBrowser是一个公共函数,该函数返回平台ID是否代表浏览器平台。

酷..通过上面的代码片段,您可以随意推广存在Window对象的防御机制,如果您在应用程序中滥用window Object,只需确保检查它是否是浏览器或服务器。有一个功能可以检查平台是否为服务器-isPlatformServer


参考资料:

1、Angular Universal: ReferenceError: window is not defined

分享到:

发表评论

评论列表