Angular Universal Server渲染WebSocket [英] Angular Universal server rendering WebSocket

查看:79
本文介绍了Angular Universal Server渲染WebSocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有带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-starter Which 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)

推荐答案

尝试仅在客户端上调用websocket,例如,您可以检测到是这些导入的浏览器还是服务器

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 Server渲染WebSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆