首页 > 解决方案 > 错误:文档未定义,构建角度通用应用程序

问题描述

错误 :

factory(require("jquery"), document, window, navigator);
                               ^ReferenceError: document is not defined

面对角度通用渲染服务器端的问题,我用谷歌搜索了这个并浏览了很多帖子,但没有得到任何有用的资源。

标签: angularangular-universal

解决方案


Jquery 在浏览器端工作,服务器端不支持浏览器功能。例如,如果您想在 Angular Universal 中使用 jquery,则必须确保仅在浏览器端使用它。

例如,您可以执行以下操作。

在您的 component.ts 文件中导入以下内容。

import { isPlatformServer } from '@angular/common';
import * as $ from 'jquery';

然后在您的 ngOnInit 函数中执行以下操作

constructor(@Inject(PLATFORM_ID) private platformId: any) {}
  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
     /* jQuery here */
     $("#test-button").click(function () {
       alert('WOOOW');
       $(this).css("background","#000");
    });
  }
}

推荐阅读