2017-10-20 137 views
0

我与图书馆NG2-MQTT工作,我用它即时我的组件是这样的:窗口没有被定义的角度普遍第三库

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

现在我得到以下错误:

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) 

我该如何解决这个问题?

+0

您可以通过使用角/可共同 –

回答

3

一种可能的方式,以避免服务器错误是不渲染成分(如果它是一个选项)使用window。喜欢的东西:

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

的isBrowser可以从(NG2

import { isBrowser } from 'angular2-universal'; 

进口或者如果NG4 +,您也可以将您的浏览器模块中的定义是:

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

然后构造注入

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!'); 
    } 
} 
0

window不应该在服务器端的通用应用程序中使用,因为Node.js没有window,并且虚拟global.window当前影响Angular检测全局变量的方式。

如果软件包使用window,则可以在其存储库中打开问题并且/或者可以将其分叉并更改为不使用window

因为依赖window的软件包通常依赖于客户端特有的东西,所以即使解决了这个问题,它们在服务器端也无法按预期工作。

Package description说:

Depends on the library from: https://eclipse.org/paho/clients/js/

虽然library description说:

The Paho JavaScript Client is an MQTT browser-based client library written in Javascript that uses WebSockets to connect to an MQTT Broker.

是不应该按预期在服务器端应存根或嘲笑

通常第三方角度模块;用假指令和服务虚拟模块在app.server.ts,而不是真正的模块导入。

+0

好isPlatformBrowser选择只在浏览器中运行的代码的这一部分,我真的不明白。有没有办法解决这个问题?我应该在Node.js应用程序中创建一个globa变量窗口,以及如何以及在哪里应该这样做? –

+0

查看最后一段。它适用于你的情况。这完全取决于模块在您的应用程序中的使用方式,即该模块如何影响服务器端生成的页面。另外,请考虑解决问题。供应商有责任提供不会在通用应用程序中导致错误的模块。 – estus

+0

我已经在回购中打开了该问题。我使用模块作为客户端,但错误发生在服务器端。我不知道我该如何解决这个问题。然而thanx您的帮助 –