问题描述
是否有使用 WebSockets 的 Angular Universal 示例?
Are there any examples of Angular Universal with WebSockets?
在我的情况下,服务器端渲染不知道 WebSocket 对象.如果我使用 socket.io,则节点服务器在尝试建立连接时会挂起.
Serverside rendering does not know wat a WebSocket object is in my case. And if I use socket.io the node server hangs when trying to make a connections.
有关问题的一些附加信息:
Some additional information about the problem:
我从 github 下载了 angular-universal-starter:https://github.com/angular/universal-首发开箱即用,运行npm install"和npm start"即可正常工作
I downloaded angular-universal-starter from github: https://github.com/angular/universal-starterWhich works fine out of the box running 'npm install' and 'npm start'
但是在我将以下代码添加到 AppComponent 之后
But after i added the following code to AppComponent
export class AppComponent implements OnInit {
ngOnInit() {
let webSocket = new WebSocket("----server url----")
}
}
我的 NodeJs 服务器控制台出现以下错误:
I got the following error in my NodeJs server console:
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)
推荐答案
尽量只在Client上调用websocket,比如通过这些import可以检测是浏览器还是服务器
Try only calling the websocket on the Client, for example you can detect whether it's the browser or the server with these imports
import { isPlatformBrowser } from '@angular/common';
import { Inject, PLATFORM_ID } from '@angular/core';
然后在您的代码中使用它们,这可能可以解决问题!
Then use them inside your code, this might be able to fix the problem!
@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----");
}
}
}
这篇关于Angular Universal 服务器渲染 WebSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!