错误:文档未定义,在构建角度通用应用程序时 [英] Error : Document not defined , On build angular universal app

查看:24
本文介绍了错误:文档未定义,在构建角度通用应用程序时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误:

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

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

Facing issue angular universal rendering server side, I have googled this and go through many posts but didn't get any helpful resource.

推荐答案

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

Jquery works on the browser side and browser functions is not supported on server side. for example if you want to use jquery in angular universal you will have to make sure you are using it on browser side only.

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

For example you can do the following.

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

In your component.ts file import the following.

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

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

and then in your ngOnInit function do the following

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

这篇关于错误:文档未定义,在构建角度通用应用程序时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆