2017-10-20 34 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您的幫助 –