窗口未定义角度通用第三库

问题描述 投票:1回答:4

我正在使用库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)

我该如何解决这个问题?

javascript angular typescript angular-universal
4个回答
5
投票

避免服务器错误的一种可能方法是不渲染使用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!');
    }
}

1
投票

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

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

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

Package description说:

取决于图书馆:https://eclipse.org/paho/clients/js/

虽然library description说:

Paho JavaScript Client是一个基于MQTT浏览器的客户端库,用Javascript编写,使用WebSockets连接到MQTT Broker。

通常应该在服务器端按预期工作的第三方Angular模块应该被存根或模拟;带有伪指令和服务的虚拟模块是在app.server.ts而不是真实模块中导入的。


1
投票

UPDATE

扩展Leon Li的答案,如果需要浏览器API(如位置或窗口),我们可以避免加载无法在服务器端呈现的组件。

This answer解释了如何使用

import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';

constructor( @Inject(PLATFORM_ID) platformId: Object) {
  this.isBrowser = isPlatformBrowser(platformId);
}

只需将PLATFORM_ID注入您的服务,并将其传递给isPlatformBrowserisPlatformServerto获取布尔值。因此,如果它们依赖于浏览器API,则可以显示/隐藏无法在服务器上呈现的组件。


0
投票

Angular 6在server.ts中使用:

const domino = require('domino');
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync('dist/browser/index.html').toString();
const win = domino.createWindow(template);

global['window'] = win;
global['document'] = win.document;
global['DOMTokenList'] = win.DOMTokenList;
global['Node'] = win.Node;
global['Text'] = win.Text;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;
© www.soinside.com 2019 - 2024. All rights reserved.