窗口未定义角度通用第三库 [英] window is not defined angular universal third library

查看:22
本文介绍了窗口未定义角度通用第三库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用库 ng2-mqtt,我在我的组件中使用它,如下所示:

 import 'ng2-mqtt/mqttws31.js';声明 var Paho: 任何;

现在我收到以下错误:

<块引用>

ReferenceError: window is not defined在对象<匿名>(/Users/Picchu/Documents/em3/node_modules/ng2-mqtt/mqttws31.js:2143:4)在 Module._compile (module.js:556:32)在 Object.Module._extensions..js (module.js:565:10)在 Module.load (module.js:473:32)在 tryModuleLoad (module.js:432:12)在 Function.Module._load (module.js:424:3)在 Module.require (module.js:483:17)在要求(内部/module.js:20:19)在对象<匿名>(/Users/Picchu/Documents/em3/dist/server.js:18707:18)

我该如何解决这个问题?

解决方案

避免服务器错误的一种可能方法是不渲染使用 window 的组件(如果它是一个选项).类似的东西:

<!-- mqttws31-component --><mqttws31-component></mqttws31-component></ng-容器>

isBrowser 可以从(ng2) 导入

import { isBrowser } from 'angular2-universal';

或者如果ng4+,你也可以在你的浏览器模块中定义:

//app.browser@NgModule({供应商: [{ 提供:'isBrowser',useValue:true }]})

然后从构造函数注入

export class SomeComponent 实现 OnInit {构造函数(@Inject('isBrowser')私有isBrowser:布尔值)ngOnInit() {//示例用法,这当然可以在此组件中的任何位置如果(this.isBrowser){alert('我们在浏览器中!');}}

I am working with the library ng2-mqtt and I used it im my component like this:

 import 'ng2-mqtt/mqttws31.js';
declare var Paho: any;

Now I am getting following error:

ReferenceError: window is not defined
    at Object.<anonymous> (/Users/Picchu/Documents/em3/node_modules/ng2-mqtt/mqttws31.js:2143:4)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/Picchu/Documents/em3/dist/server.js:18707:18)

How can I fix this issue?

解决方案

One possible way to avoid server error is not to render the component(if it is an option) that uses window. Something like:

<ng-container *ngIf="isBrowser">
   <!-- mqttws31-component -->
   <mqttws31-component></mqttws31-component> 
</ng-container>

The isBrowser can be imported from(ng2)

import { isBrowser } from 'angular2-universal';

Or if ng4+, you can also define this in your browser module:

// app.browser
@NgModule({
  providers: [
    { provide: 'isBrowser', useValue: true }
  ]
})

then inject from constructor

export class SomeComponent implements OnInit {
  constructor(@Inject('isBrowser') private isBrowser: boolean)
  ngOnInit() { 
    // example usage, this could be anywhere in this Component of course
    if (this.isBrowser) { 
      alert('we're in the browser!');
    }
}

这篇关于窗口未定义角度通用第三库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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