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

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

问题描述

错误:

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

面对角度通用渲染服务器端的问题,我已经在Google上进行了搜索,并浏览了许多帖子,但没有获得任何有用的资源.

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天全站免登陆