Mar*_*rco 7 websocket node.js socket.io angular-universal angular
是否有任何带WebSockets的Angular Universal示例?
在我的情况下,Serverside渲染不知道WebSocket对象.如果我使用socket.io,节点服务器在尝试建立连接时会挂起.
有关此问题的一些其他信息:
我从github下载了角度通用启动器:https://github.com/angular/universal-starter 运行'npm install'和'npm start'的开箱即用
但在我将以下代码添加到AppComponent之后
export class AppComponent implements OnInit {
ngOnInit() {
let webSocket = new WebSocket("----server url----")
}
}
Run Code Online (Sandbox Code Playgroud)
我的NodeJs服务器控制台中出现以下错误:
EXCEPTION: WebSocket is not defined
ORIGINAL STACKTRACE:
ReferenceError: WebSocket is not defined
at AppComponent.ngOnInit (/Volumes/Development/cacadu/website/universal-starter-master2/dist
/server/index.js:41725:29)
Run Code Online (Sandbox Code Playgroud)
尝试只在客户端调用websocket,例如您可以通过这些导入来检测是浏览器还是服务器
import { isPlatformBrowser } from '@angular/common';
import { Inject, PLATFORM_ID } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)
然后在代码中使用它们,这也许可以解决问题!
@Component({ ... })
export class AppComponent implements OnInit {
private isBrowser: boolean = isPlatformBrowser(this.platformId);
constructor(
@Inject(PLATFORM_ID) private platformId: Object
) {
if (isBrowser) {
let webSocket = new WebSocket("----server url----");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1101 次 |
| 最近记录: |